Giter VIP home page Giter VIP logo

wordcloud2.js's Introduction

wordcloud2.js npm version

Create a tag cloud/Wordle presentation on 2D canvas or HTML.

This library is a spin-off project from HTML5 Word Cloud.

Visit the demo page

Installation

npm install wordcloud

Simple usage

Download the latest wordcloud2.js file from the src folder in this repository.

Load wordcloud2.js script to the web page, and run:

WordCloud(document.getElementById('my_canvas'), { list: list } );

where list is an array that look like this: [['foo', 12], ['bar', 6]].

Options available, see API documentation for detail.

Contact & help

Please read through the API documentation and CONTRIBUTING.md before filing an issue or contact me via e-mail.

Algorithm

Before putting each word on the canvas, it is drawn on a separate canvas to read back the pixels to record is drawn spaces. With the information, wordcloud.js will then try to find a place to fit the word that is closest to the start point.

Testing

Tests are available with QUnit and grunt. To setup environment for testing, run npm install and manually install SlimerJS of your platform.

Use grunt test to ensure all options can be set without JavaScript error.

Use grunt compare --base-commit=gh-pages to compare your proposed fix with gh-pages branch.

Acknowledgement

The developer would like to thank Chad Jensen for sponsoring the work on image masking on the demo page.

wordcloud2.js's People

Contributors

adityanaag3 avatar aeradriel avatar alexjf avatar bigomega avatar brandoncc avatar daithi-coombes avatar dandv avatar dependabot[bot] avatar dominikherold avatar fensterbank avatar floriansw avatar frankmayer avatar harrisonpage avatar jacquimanzi avatar jes490 avatar kernc avatar kyoloro avatar maman avatar mibamur avatar mstevens avatar orapouso avatar peterdavehello avatar pirosauro avatar rse avatar seanmcmillan avatar steel avatar stefan-it avatar stephenr85 avatar tiagofscoelho avatar timdream avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

wordcloud2.js's Issues

Hover - Uncaught TypeError

Whenever I hover an empty area of a wordcloud canvas, normally on the left side and very close to the border, I keep on receiving this error:

Uncaught TypeError: Cannot read property '[ANY NUMBER]' of undefined
getInfoGridFromMouseTouchEvent @ wordcloud2.min.js
wordcloudhover @ wordcloud2.min.js

tooltip on hover

Hi,

First of all, thank you for this great tool. I am not so advanced in JS and this allowed me to make a great Tag Cloud for my website.

I have a been working all day on trying to get the jQuery Tooltip to work without success. It is working well on a "test"

that never changes in the HTML page with the following JS code:

$("#tooltip-2").tooltip({
                content: "<strong>Hello!</strong>",
                track:true
});

But I can't make it work with the hover function of your tool. I was able to get the basic tooltip from the browser with the correct text inside by changing the title of the "box" div but this obviously gives me enough option to get a decent tooltip (I base my code on your example where you draw a box around the hovered text).

My code looks like that:

window.setText = function setText(item, dimension) { 
    if (!dimension) {
        $box.prop('hidden', true); 
        return;
    } 
    $('#wordcloud').attr('title', item[0]); 
}

options.hover = window.setText; 

I tried to put something like that a bit everywhere in the code (inside the function, outside, etc..) but nothing works:

$("#wordcloud").tooltip({
                content: "Hi!",
                track:true
});

Any ideas?
Thx

Shape generator not working

I uploaded a black and white image but as soon as I loaded it appears a black and green image. Isn't there a more simple way to create a custom shape? Or am I doing something wrong?

I'll be using the Silhouette of a men and a women....this is an image I tried it out with (Not the one I'll be using, just for testing)...
sin titulo
this is what it shows:
image

Text box width, which would allow multiline phrases

Is there anyway to limit the width of the text box to a few words or a certain number of pixels? I've gone through the source and can't see how I would do this. I have longer phrases (3-8 words) that I'd love to make into a cloud as multiline 'chunks' of text. Right now they're all single lines which really doesn't work. Tips, tricks appreciated. ;-)

Example "Web Technologies" does not support HOVER on IE 9-10 / FIXED

please replace " $box.prop('hidden', true);" and "$box.prop('hidden', false);" with " $box.hide();" and "$box.show();"

    window.drawBox = function drawBox(item, dimension) {
      if (!dimension) {
        $box.prop('hidden', true);

        return;
      }

      var dppx = $dppx.val();

      $box.prop('hidden', false);
      $box.css({
        left: dimension.x / dppx + 'px',
        top: dimension.y / dppx + 'px',
        width: dimension.w / dppx + 'px',
        height: dimension.h / dppx + 'px'
      });
    };

Real time update the wordcloud

According to the sample code,
WordCloud(document.getElementById('my_canvas'), { list: list } );

If I get the array 'list' from my MYSQL database, and show on my web, this works perfectly. But how can I refresh the wordcloud while just one more data is added to the array "list"? I dont think refresh the whole php is good, as my array 'list' is quite big, so that the animation time for they all appear is a bit long.

Is there an effective way to implement a real time update wordcloud?

wordcloud2 on div?

hi,
on I get a beautiful cloud, but when I change the tag to

there's nothing
(checked the HTML with firebug - nothing built)

why?

thanks

rraa17

container offset process

please add el.offsetLeft and el.offsetTop like this:

 var styleRules = {
...
        'left': el.offsetLeft + ((gx + info.gw / 2) * g + info.fillTextOffsetX) + 'px',
        'top': el.offsetTop + ((gy + info.gh / 2) * g + info.fillTextOffsetY) + 'px',
...

Crashes on large word sizes

If the size for a word is too large, the script will crash on line 509 of the getTextInfo method, ie:

// Get the pixels of the text
var imageData = fctx.getImageData(0, 0, width, height).data;

...giving this error:

Cannot read property 'data' of null

It can be duplicated by running this on a 800px x 1200px canvas:

WordCloud( myCanvas, { list : [["my",173],["spoon",283],["is",173],["too",283],["big",6283]] });

I may be mistaken, but my expected behavior was that the entire cloud would scale down so that the extra large word(s) fit.

This happens in Chrome, I have not tested other browsers.

Hover Canvas/HTML Target

I'm having a problem with hover event in my word clouds. Actually I don't know if it depends on the position of the parent elements or something like this, but the event is almost never returning the correct word I'm hovering on both canvas and HTML. On a canvas contained in a right floating div the event is not even firing.

Too Large Words not Shown

Hi, I'm building my wordlist from a database and calculating the weight from the number of occurrences.
I'm having an issue where if the word is extremely frequent then the word becomes so large it's no longer shown. Is there an option to make sure no word grows so large it can't be displayed, or a method to proportionally size the words working backwards from the largest word?

Thanks!

Problem with window zoom

Steps to reproduce:

Increase Window zoom in Chrome to 110% or higher and load up http://timdream.org/wordcloud2.js/#love

You'll notice that the JS goes into an infinite loop and refuses to render any wordclouds. I've narrowed it down to the grid detection code in getTextInfo however I'm not familiar enough with your code to go much further.

Noting is showing up

I tried what was in the Simple usage, but still nothing showing up.
< div id="my_canvas" >< /div >
< script >
var list = [['foo', 12], ['bar', 6]];
WordCloud(document.getElementById('my_canvas'), { list: list } );
< /script >

Hover over word element broken for non HTML5 canvas word clouds

I am getting a Uncaught TypeError: Cannot read property 'NaN' of undefined when using the hover callback.

Digging into the code I see this:

var getInfoGridFromMouseEvent = function getInfoGridFromMouseEvent(evt) {
      var canvas = evt.target;
      var rect = canvas.getBoundingClientRect();
      var eventX = evt.clientX - rect.left;
      var eventY = evt.clientY - rect.top;

      var x = Math.floor(eventX * (canvas.width / rect.width) / g);
      var y = Math.floor(eventY * (canvas.height / rect.height) / g);

      return infoGrid[x][y];
    };

In my particular case, var canvas = evt.target; is not an HTML5 canvas element and does not have a .width or .height property. This does work if I place my word cloud in an HTML5 canvas, however.

Click setting

Hi,

First off, thanks for making this excellent plugin!

I had a question, is there any way to call each word on click.

Thank you in advance.

Any way to have two of the same word?

I'd like to display the same word multiple times with different sizes (i'm using coloring to differentiate between one instance and another) is there any way of doing that in the current api?

The reasoning behind doing this is that I want to combine the word clouds of two documents into a single cloud, but still be able to see the difference in relative frequency between two instances of say "good".

interactive

provide hover and click callback for canvas... it will be fun!

click event broken for HTML (non-canvas) rendering (ad-hoc ugly fix included)

The "click" event is broken (the code fails with an exception on line return infoGrid[x][y];because infoGrid is not filled for the plain HTML case at all) in case one renders plain HTML (the non-canvas variant), because the internal getInfoGridFromMouseEvent() function is not aware of the plain HTML case at all. For my case (where I don't need the dimension information at all) I've ugly fixed it the following way:

--- bower_components/wordcloud2.js/src/wordcloud2.js    2014-03-22 19:06:16.000000000 +0100
+++ lib/wordcloud2/wordcloud2.js    2014-03-23 09:02:47.811057186 +0100
@@ -349,6 +369,12 @@

     var getInfoGridFromMouseEvent = function getInfoGridFromMouseEvent(evt) {
       var canvas = evt.target;
+      if (!canvas.getContext) {
+          var i = $(canvas).text();
+          var d = { x: 0, y: 0, w: 0, h: 0 }; /* FIXME */
+          var info = { item: i, dimension: d };
+          return info;
+      }
       var rect = canvas.getBoundingClientRect();
       var eventX = evt.clientX - rect.left;
       var eventY = evt.clientY - rect.top;

Please fix this similar to this attempt, but with a correct dimension, too. Thanks.

please tag a release

Hi could you please tag a release version for this library ? it would help with my package manager.

Color individual item

Hi, thanks for a great plugin!
I was wondering whether this is possible in any way:

Is there any way to color individual item with for example a third attribute in the list or the color callback-function is able to return a saved custom attribute?

Something like this:
[0: "Word",1: 6, color: "#00b2ee"] or [0: "Word",1: 6, 2: "#00b2ee"]

Or, like this:
color: function (customAttribute) {
return customAttribute.color; or return element.customAttribute
}

Examples on non-radial shapes?

Hi Tim,

Is it possible to have non-radial shapes for wordclouds? Your shape-generator.html is a nice tool for generating new wordcloud shapes, but the process is based on drawing lines from one central point.
For example: I'd like to have a shape of a world map. Does wordcloud2.js support such 'arbitrary' shapes? If so, how do I generate the coordinates for the "theta" function?
Do you maybe have some examples?

Problem with Chrome and Win8.1?

Hello, I use your wonderful wordcloud for http://www.floskelwolke.de

By chance I could see a post on G+ (https://plus.google.com/u/0/+borgdrone/posts/W9f5PQ6gdBv), where the font is incorrect, curiously only with the biggest keyword.

The one, who made the screenshot, told me, he uses Win 8.1 and Chrome.

I have Win7 and tested it also with Google Chrome and couldn't see any probs with the font which is embedded via google fonts.

Is it a known bug? Or why does this appear?

Regards
Sebastian

Unit tests for setImmediate

It would be nice if we could verify window.setImmediate() shim/native implementation works on a given browser.

NS_ERROR_FAILURE with no line information, reproducible from a dataset

I have a dataset, a collection of tweets containing the word "climate" over a few hours. This dataset, when dumped into WordCloud renders a cloud alright, but the most used word never appears. In fact, a lot of words that shouldn't be in the top 10 are rendering very large. It also doesn't finish, dumping out an NS_ERROR_FAILURE in the console.

In an effort to make sure that only the most relevant words made it into the cloud, I sorted the array by the frequency value and chopped off everything but the first 500, 200, 100, and even 50 entries. The result in every case was that the word cloud doesn't even begin to render and just dumps NS_ERROR_FAILURE into the console from the start.

I've created a demo here if you'd like to see what's happening. Perhaps this is due to the fact that climate appears so often (obviously), but I'm unsure of how to modify the data set to play nice with WordCloud, or if this is indeed a bug.

Enhancement: allow fontWeight and fontFamily to be callbacks, too

I wanted to render a wordcloud where the words use different(!) font families and weights. This is not supported, but can easily be supported similar to the way the individual coloring is supported: with the help of callback functions. Find below my enhancement which does exactly this (only documentation update missing, but code is complete):

--- bower_components/wordcloud2.js/src/wordcloud2.js    2014-03-22 19:06:16.000000000 +0100
+++ lib/wordcloud2/wordcloud2.js    2014-03-23 09:02:47.811057186 +0100
@@ -342,6 +342,26 @@
         break;
     }

+    /* convert fontFamily into a function */
+    if (typeof settings.fontFamily !== 'function') {
+      (function () {
+        var value = settings.fontFamily;
+        settings.fontFamily = function fontFamily(word) {
+          return value;
+        };
+      })();
+    }
+
+    /* convert fontWeight into a function */
+    if (typeof settings.fontWeight !== 'function') {
+      (function () {
+        var value = settings.fontWeight;
+        settings.fontWeight = function fontWeight(word) {
+          return value;
+        };
+      })();
+    }
+
     /* Interactive */
     var interactive = false;
     var infoGrid = [];
@@ -465,7 +491,7 @@
       var fcanvas = document.createElement('canvas');
       var fctx = fcanvas.getContext('2d', { willReadFrequently: true });

-      fctx.font = settings.fontWeight + ' ' + (fontSize * mu).toString(10) + 'px ' + settings.fontFamily;
+      fctx.font = settings.fontWeight(word) + ' ' + (fontSize * mu).toString(10) + 'px ' + settings.fontFamily(word);

       // Estimate the dimension of the text with measureText().
       var fw = fctx.measureText(word).width / mu;
@@ -514,7 +540,7 @@

       // Once the width/height is set, ctx info will be reset.
       // Set it again here.
-      fctx.font = settings.fontWeight + ' ' + (fontSize * mu).toString(10) + 'px ' + settings.fontFamily;
+      fctx.font = settings.fontWeight(word) + ' ' + (fontSize * mu).toString(10) + 'px ' + settings.fontFamily(word);

       // Fill the text into the fcanvas.
       // XXX: We cannot because textBaseline = 'top' here because
@@ -646,8 +672,8 @@
           ctx.save();
           ctx.scale(1 / mu, 1 / mu);

-          ctx.font = settings.fontWeight + ' ' +
-                     (fontSize * mu).toString(10) + 'px ' + settings.fontFamily;
+          ctx.font = settings.fontWeight(word) + ' ' +
+                     (fontSize * mu).toString(10) + 'px ' + settings.fontFamily(word);
           ctx.fillStyle = color;

           // Translate the canvas position to the origin coordinate of where
@@ -689,8 +715,8 @@
           var styleRules = {
             'position': 'absolute',
             'display': 'block',
-            'font': settings.fontWeight + ' ' +
-                    (fontSize * info.mu) + 'px ' + settings.fontFamily,
+            'font': settings.fontWeight(word) + ' ' +
+                    (fontSize * info.mu) + 'px ' + settings.fontFamily(word),
             'left': ((gx + info.gw / 2) * g + info.fillTextOffsetX) + 'px',
             'top': ((gy + info.gh / 2) * g + info.fillTextOffsetY) + 'px',
             'width': info.fillTextWidth + 'px',

Manual for Shape Generator?

Hi,

is there any documentation for the shape generator?

I have something like this:

function(theta) {
  var max = 1901;
  var leng = [1877,1880,1881, ...];

  return leng[(theta / (2 * Math.PI)) * leng.length | 0] / max;
}

How to install this to wordcloud2.js?

Scale of word value?

Hi!
May I know what how the range of value is mapped to the size of word drawn please? I put the value in a scale of [50,100] and [500,1000] but they ended up shown the size of ants....
I didn't use weight factors or minimal font size etc in the parameters, just passed in a list with all value scaled. It there a suggested value range with all other parameters by default? Or shall I just go ahead and increase the weightFactor etc?
Thanks in advance!

How to make sure all words are displayed in canvas

Thanks for your very good plugin!

In my case, the weight of each words is a number of occurrences. I use the weightFactor function in order to normalize it. The problem is depending on the rotation random some big weighted words are shown or not.
I can change de size of my canvas but by doing so I have sometimes big empty places.

  • Having some normalize functions choices would be a good enhancement (linear, exp, ..., custom).
  • Being able to have the size (height or width) of the canvas calculated automatically would be good as well.. Maybe having a function for rotation would be a solution since you can choose if you want to rotate depending on the weight...
  • I spent quite some time on your wordcloud code looking for a way to have the hover word highlighted. I found your fixed issue but no explanation on how to do so. At the end I found that you use a absolute div (no pointer-event) that you place using dimensions provided by the hover callback. You should say it in your doc :)

Thanks again

Visual for hover

We should somehow be able to highlight the word that is currently being hovered to indicate it's click-ability -- at least we should expose the information for external script to draw such visual.

WordCloud not showing if all words have same frequency

Hi,

I've done some testing with your library, and I seems to have stumbled on a bug. If all the words of the list have the same frequency, then the cloud will not show up and a javascript exception will be thrown :

TypeError: Argument 3 of CanvasRenderingContext2D.getImageData is not a finite floating-point value.

i.e : [['Internet', 3], ['Google', 3], ['Web', 3]]

Making a WordCloud with these frequencies will not work. (Unless I'm doing something wrong? My WordCloud usually appears, but not with these values)

Background-Shapes for each Tag

There is an interesting and easy way to form a cloud-shape with CSS3 (http://thecodeplayer.com/walkthrough/make-a-simple-cloud-in-css3). I would really like to implement this (or any other way to build 'clouds') into wordcloud.js... as a background for each tag/text. And, of course, the clouds will resident, too, and there must not be an overlapping. That would look really awesome, I think. Do you think, it's possible (maybe with the span-option)?

onClick showing the wrong word

Hi,

Thank you for the great library!

I'm having a small problem, my onClick event is showing the wrong word.
You can see the problem here: http://jsbin.com/fojiwituxa/edit?js,output

My initialization code is very simple:

WordCloud(document.getElementById('c'), {
                list: list_english,
                ellipticity: 1.5,
                hover: function(item, dimension, event) {
                    //console.log(event);
                },
              click: function(item) {
                alert(item[0] + ': ' + item[1]);
              }
            });

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.