wordcloud2.js

repository·gh-pages·Indexed 25 days ago

https://github.com/timdream/wordcloud2.js

A JavaScript library for creating tag clouds or Wordle-style presentations on a 2D canvas or within HTML. It supports various shapes (circle, cardioid, diamond, square, triangle, pentagon, star), custom font configurations, and interactive hover and click events. The library provides the WordCloud() function for rendering and utility methods like WordCloud.stop() and WordCloud.isSupported to manage the generation process and environment compatibility.

Tokens
2.2K
Snippets
3
Records
18
Agent score
80%

What's inside wordcloud2.js

  1. Create a simple word cloud

    gh-pages

    To create a word cloud, download wordcloud2.js from the src folder, include it in your web page, and call the WordCloud function.

    Pass a canvas element (or an HTML element) as the first argument and an options object as the second. The options object must contain a list key, which is an array of arrays where each inner array contains a string (the word) and a number (its weight/size).

  2. Use interactive features with hover and click

    gh-pages

    To enable interactivity, provide hover and/or click functions in the options object. When these are provided, the library tracks word positions in an internal infoGrid to map mouse events to specific words.

    • hover(item, dimension, event): Triggered when the mouse moves over a word. item is the original data item, and dimension contains the bounding box {x, y, w, h}.
    • click(item, dimension, event): Triggered when a word is clicked.

    Note: Interactivity works on both <canvas> and <div> elements.

  3. Configure word cloud randomness and interaction

    gh-pages

    Control randomness and user interaction:

    Randomness

    • shuffle: If true, shuffles points to ensure different results for the same list.
    • rotateRatio: Probability of a word rotating (set to 1 to always rotate).

    Interaction

    • hover: Callback for cursor entry/exit: callback(item, dimension, event).
    • click: Callback for word clicks: callback(item, dimension, event).
  4. Configure word cloud presentation options

    gh-pages

    The options object supports several presentation settings:

    • list: A 2D array of [word, size] pairs. You can append extra data for callbacks: [['foo', 12, 'extra-data'], ['bar', 6]].
    • fontFamily: The font to use.
    • fontWeight: Font weight (e.g., 'normal', 'bold', '600') or a callback: callback(word, weight, fontSize, extraData).
    • color: CSS color, built-in keywords ('random-dark', 'random-light'), or a callback: callback(word, weight, fontSize, distance, theta). For DOM clouds, setting this to null allows CSS-based customization.
    • classes: For DOM clouds, defines the class of the <span> elements. Can be a string or a callback: callback(word, weight, fontSize, extraData).
    • minSize: Minimum font size.
    • weightFactor: A number or function to multiply the size of each word.
    • clearCanvas: If true, clears the canvas before starting.
    • backgroundColor: Background color.
  5. Configure word cloud dimension and shape options

    gh-pages

    Control the layout and boundaries of the cloud:

    • gridSize: Pixel size of the grid used for marking availability (larger values increase gaps between words).
    • origin: The [x, y] origin of the cloud.
    • drawOutOfBound: If true, allows words to be drawn partially outside the canvas or larger than the canvas.
    • shrinkToFit: If true, shrinks words to fit the canvas (note: this reduces the word's weight).
    • shape: The cloud shape. Keywords: 'circle' (default), 'cardioid', 'diamond', 'square', 'triangle-forward', 'triangle' (alias of 'triangle-upright'), 'pentagon', and 'star'. Can also be a polar equation callback.
    • ellipticity: Degree of flatness for the shape.
  6. Configure word cloud timing and rotation

    gh-pages

    Manage the rendering lifecycle and text orientation:

    Timing

    • wait: Milliseconds to wait before drawing the next item via setTimeout.
    • abortThreshold: If a loop iteration takes longer than this many milliseconds, the rendering aborts.
    • abort: Callback function executed when an abort occurs.

    Rotation

    • minRotation: Minimum rotation in radians.
    • maxRotation: Maximum rotation in radians. Set both to the same value for a fixed angle.
    • rotationSteps: Forces a specific number of angles (e.g., setting to 2 in a -90°/90° range uses only -90, 0, or 90).
  7. Stop word cloud rendering

    gh-pages

    To optimize performance (for example, when a component unmounts in React), you can stop the current rendering process by calling WordCloud.stop().

    useEffect(() => {
      ...
      return () => {
        // stop the renderring
        WordCloud.stop();
      };
    }, [deps]);
  8. Check browser support and minimum font size

    gh-pages

    Use the following properties to detect environment capabilities:

    • WordCloud.isSupported: Returns false if the browser lacks the necessary functionalities to run the library.
    • WordCloud.minFontSize: Returns the value of the browser's minimum font size preference, which may impact canvas rendering.
  9. Generate a word cloud with WordCloud()

    gh-pages

    To render a word cloud, call the WordCloud(elements, options) function.

    elements can be a single DOM element (like a <canvas> or a <div>), an array of DOM elements, or a jQuery object.

    • If a <canvas> element is provided, the cloud is rendered as an image on the canvas.
    • If any other element is provided, the cloud is rendered as a collection of <span> elements (a DOM cloud), which allows for further CSS styling.

    options is an object containing configuration settings for the cloud's appearance and behavior.

    WordCloud(elements, options);
  10. Configure WordCloud options

    gh-pages

    The options object allows you to customize the appearance and behavior of the word cloud.

    Common Configuration Keys:

    • list: An array of words and weights. Each item can be an array ['word', weight] or an object {word: 'word', weight: weight, attributes: {}}.
    • fontFamily: CSS font family string.
    • fontWeight: CSS font weight string or a function (word, weight, fontSize, extraData) => string.
    • color: Color specification. Supports 'random-dark', 'random-light', or a function (word, weight, fontSize, distance, theta, extraData) => string.
    • minSize: Minimum font size (0 to disable).
    • weightFactor: A number or a function (weight) => fontSize to determine font size.
    • backgroundColor: Background color (e.g., '#fff').
    • gridSize: Integer (minimum 4) defining the grid resolution for placement.
    • shape: The cloud shape. Supports 'circle' (default), 'cardioid', 'diamond', 'square', 'triangle-forward', 'triangle', 'triangle-upright', 'pentagon', 'star', or a custom function (theta) => radius.
    • rotateRatio: Probability (0 to 1) that a word will be rotated.
    • minRotation / maxRotation: Range of allowed rotation in radians.
    • shrinkToFit: Boolean. If true, words that don't fit will have their weight reduced and retried.
    • hover: Function (item, dimension, event) => void for mouseover interaction.
    • click: Function (item, dimension, event) => void for click interaction.
    • classes: Function (word, weight, fontSize, extraData) => string to assign CSS classes to words.
    • abort: Function called if the drawing process is aborted.