timdream / wordcloud2.js

Tag cloud/Wordle presentation on 2D canvas or HTML
https://wordcloud2-js.timdream.org/
MIT License
2.36k stars 511 forks source link

Draw multiple wordclouds in one canvas #89

Open fusiwei339 opened 7 years ago

fusiwei339 commented 7 years ago

I'm trying to draw multiple wordclouds in one canvas. Below is the sample code.

           function drawWordCloud(canvas, i) {
                var option = {
                    list[i], //each word cloud has different word list
                    clearCanvas: false,
                    origin[i], //assign each word cloud a different origin
                }
                WordCloud(canvas, option)
           }
           for (let i = 0; i < n; i++) {
                drawWordCloud(canvas, i)
           }

The result is not correct. That is, only the last wordcloud is drawn. When I debug the code, I find that the problem relates to wordcloud2.js, especially in timer, window.setTimeout, window.clearTimeout (from line 1108 to line 1159). To solve this problem, I change the code as:

           function drawWordCloud(canvas, i) {
                var option = {
                    list[i], //each word cloud has different word list
                    clearCanvas: false,
                    origin[i], //assign each word cloud a different origin
                }
                WordCloud(canvas, option)
           }
           function delayDrawing(i) {
                setTimeout(function() {
                    drawWordCloud(canvas, i)
                }, 1000)
           }
           for (let i = 0; i < n; i++) {
                delayDrawing(i)
           }

Now it works. Multiple wordclouds are drawn in the same canvas. However, I have to wait for a long time until it finishes.

Do you have any suggestions?

Thank you!

timdream commented 7 years ago

Thanks for filing. Each of the instance has it's own 2-d array that keep the area of undrawn area. The text would over each other if you try to draw it at the same time. I would recommend you draw the cloud on different <canvas> element that positioned at the same place with CSS. If you set the background as transparent you will get the same result but the text will be able to draw at the time.

fusiwei339 commented 7 years ago

Thank you for your prompt reply! I'll try your method and see how it works.

BTW, I have tried many wordcloud libraries (in Java and Javascript) and have implemented one by myself (using force-directed layout + collision detection). this library is the best in its functionality and robustness. And the source code is elegant. I really appreciate @timdream 's work!