D3 Word Cloud Layout

1.2.9 · maintenance · verified Sun Apr 19

d3-cloud is a JavaScript library for generating Wordle-inspired word clouds, leveraging HTML5 canvas and sprite masks for efficient rendering. It provides a programmatic API to configure cloud properties such as size, word list, font face, font style, font weight, and font size accessor functions. The library integrates well within the D3.js ecosystem, although it can be used standalone to generate word layouts. The current stable version is 1.2.9, indicating a mature and stable codebase rather than one undergoing rapid iterative development. Key differentiators include its canvas-based approach for performance and its comprehensive layout algorithm that handles word placement and collision detection, contrasting with purely SVG-based solutions or those requiring manual positioning. Its primary output is an array of word objects with calculated positions, sizes, and rotations, ready for custom rendering.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to configure and run the d3-cloud layout, setting dimensions, words, font properties, and handling the 'end' event to retrieve the placed words.

import cloud from 'd3-cloud';

interface Word {
  text: string;
  value: number;
  size?: number;
  x?: number;
  y?: number;
  rotate?: number;
  font?: string;
  style?: string;
  weight?: string;
}

const wordsData: Word[] = [
  { text: "TypeScript", value: 60 },
  { text: "JavaScript", value: 50 },
  { text: "D3", value: 45 },
  { text: "Cloud", value: 40 },
  { text: "Canvas", value: 35 },
  { text: "Layout", value: 30 },
  { text: "Example", value: 25 },
  { text: "Development", value: 20 },
  { text: "Web", value: 15 },
  { text: "Visualization", value: 55 }
];

const width = 960;
const height = 500;

// Create a new cloud layout instance
const layout = cloud<Word>()
  .size([width, height])
  .words(wordsData)
  .padding(5)
  .rotate(() => Math.floor(Math.random() * 5) * 30 - 60) // Rotate words by -60, -30, 0, 30, 60 degrees
  .font("Impact")
  .fontSize(d => Math.sqrt(d.value) * 8) // Scale font size based on word value
  .on("end", (words: Word[], bounds: [{ x0: number, y0: number }, { x1: number, y1: number }]) => {
    console.log("Word cloud layout generation complete.");
    console.log("Successfully placed words:", words.map(w => ({ text: w.text, size: w.size, x: w.x, y: w.y, rotate: w.rotate })));
    console.log("Overall cloud bounds:", bounds);
    // In a real application, you would typically render these 'words' to an HTML5 Canvas or SVG element.
  });

layout.start(); // Start the layout algorithm

view raw JSON →