timdream / wordcloud2.js

Tag cloud/Wordle presentation on 2D canvas or HTML

Home Page:https://wordcloud2-js.timdream.org/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

is it possible to make a wordcloud with links?

ZXoho opened this issue · comments

commented

hello!
is it possible to make a wordcloud with links that i can click them

Hi @ZXoho! I'm not sure what do you mean about 'links', but you can add 'click' as option with callback function. Example:

function callbackFn(item) {
  console.log(item);
}

WordCloud(document.getElementById('cloud'), { 
  list: list, 
  click: (item) => { callbackFn(item); }
});

Wasn't it the image map that @ZXoho meant? It is mentioned here https://www.wordclouds.com/faq/

If you want legit links, where the desination shows in the browser statusbar, and you can open them in new tab, etc, I did this (requires jQuery, but could be rewritten):

              canvas.addEventListener('wordcloudstop', function (e) {
                   $('.tag-cloud-item').each(function () {
                       var text = $(this).html();;
                       $(this).html('<a href="/keyword/' + text + '">' + text + '</a>');
                   });
                });

                var list = [['foo', 12], ['bar', 6]]; // example list
               WordCloud(canvas, document.getElementById('my_canvas'), { list: list, classes: 'tag-cloud-item' });

To preserve the cloud span colors, use this style:

<style>
        .tag-cloud-item a{
            color:inherit;
        }
</style>

Thanks for the tip @Derrick- ! I rewrote it in vanilla JS, works like a charm!

const tagCanvas = document.querySelector("#tag-wrapper"); // select your element to draw in
WordCloud(document.querySelector("#tag-wrapper"), {
    list: tagArray,
    classes: "tag-cloud-item", // add a class to each tag element so we can easily loop over it
});

tagCanvas.addEventListener('wordcloudstop', function (e) {
    // loop over all added elements (by class name)
    document.querySelectorAll('.tag-cloud-item').forEach(function (element) {
        const text = element.innerHTML;
        element.innerHTML = `<a href="/tags/${text}" style="color: inherit;">${text}</a>`;
    });
});

https://blog.cubieserver.de/2020/adding-a-tag-cloud-to-my-hugo-blog/