DEV Community

Cover image for Word Cloud Layout in JavaScript: Weighting, Spiral Packing, and Shape Masks
YananLee
YananLee

Posted on AI-assisted

Word Cloud Layout in JavaScript: Weighting, Spiral Packing, and Shape Masks

A word cloud looks like a toy. Getting one to look good is a small but genuinely interesting engineering problem: you are packing differently-sized rectangles into a bounded region, in descending priority order, while keeping the result visually balanced.

Under the hood there are four steps — weighting, font scaling, spiral placement with collision detection, and shape masking. Here's how they fit together, with plain JavaScript you can paste into a canvas.

1. Turn text into weights

const STOP = new Set([
  'the', 'and', 'of', 'to', 'a', 'in', 'is', 'it', 'you', 'that',
  'for', 'on', 'with', 'as', 'be', 'at', 'by', 'this', 'are', 'or',
  'from', 'but', 'not', 'we', 'your', 'can', 'my', 'all', 'was', 'one'
]);

function weigh(text) {
  const counts = new Map();
  const tokens = text.toLowerCase().match(/[\p{L}\p{N}']+/gu) ?? [];
  for (const token of tokens) {
    if (token.length < 2 || STOP.has(token)) continue;
    counts.set(token, (counts.get(token) ?? 0) + 1);
  }
  return [...counts]
    .map(([word, count]) => ({ word, count }))
    .sort((a, b) => b.count - a.count);
}
Enter fullscreen mode Exit fullscreen mode

The \p{L} Unicode property escape matters: [a-z]+ silently drops every non-Latin word. Stopwords matter just as much — without them your cloud is 40% "the" and "and".

For real corpora, raw counts are usually replaced with TF-IDF so that a document about one topic doesn't just repeat its own jargon.

2. Don't scale font size linearly

The naive approach maps count directly onto size. It fails immediately: a word appearing 200 times next to words appearing 3 times gives you one giant word and a hundred invisible ones.

Compress the range first:

function addSizes(items, min = 12, max = 96) {
  const hi = Math.sqrt(items[0].count);
  const lo = Math.sqrt(items.at(-1).count);
  for (const it of items) {
    const t = hi === lo ? 1 : (Math.sqrt(it.count) - lo) / (hi - lo);
    it.size = Math.round(min + t * (max - min));
  }
}
Enter fullscreen mode Exit fullscreen mode

sqrt is a good default; log1p compresses harder. Both keep the tail readable instead of letting the top word eat the canvas.

3. Place words on an Archimedean spiral

This is the heart of it. Sort by weight (largest first), start at the center, walk outward along a spiral, and at each candidate point ask: does this word's bounding box overlap any box I've already placed? First fit wins.

const overlaps = (a, b) =>
  a.x < b.x + b.w && a.x + a.w > b.x &&
  a.y < b.y + b.h && a.y + a.h > b.y;

function layout(items, ctx, { width, height, padding = 2 }) {
  const placed = [];
  const cx = width / 2, cy = height / 2;

  for (const it of items) {
    ctx.font = `${it.size}px sans-serif`;
    const w = ctx.measureText(it.word).width + padding * 2;
    const h = it.size * 1.2 + padding * 2;

    for (let t = 0; t < 100; t += 0.08) {
      const r = 6 * t;
      const x = cx + r * Math.cos(t) - w / 2;
      const y = cy + r * Math.sin(t) - h / 2;
      const box = { x, y, w, h };

      if (x < 0 || y < 0 || x + w > width || y + h > height) continue;
      if (placed.some(p => overlaps(p, box))) continue;

      placed.push({ ...it, ...box });
      break;
    }
  }
  return placed;
}
Enter fullscreen mode Exit fullscreen mode

Why a spiral? It fills the center first, which is where the eye goes, then naturally degrades into a looser outer ring. Silently skipping a word that never fits is also fine — by then the canvas is full and smaller words would only add noise.

Two things this sketch leaves out: rotation (for vertical words, swap w and h before testing) and speed (a quadtree or spatial grid turns the linear placed.some(...) scan into something that scales past a few hundred words).

4. Cut the result into a shape

Shape clouds reuse the same packer with one extra constraint. Rasterize a transparent PNG into an alpha grid, then reject a candidate box when its corners fall outside the mask:

function makeMask(image, width, height) {
  const c = document.createElement('canvas');
  c.width = width; c.height = height;
  const g = c.getContext('2d');
  g.drawImage(image, 0, 0, width, height);
  const data = g.getImageData(0, 0, width, height).data;
  return (x, y) =>
    data[(Math.floor(y) * width + Math.floor(x)) * 4 + 3] > 128;
}

const insideMask = (box, mask) =>
  [[box.x, box.y], [box.x + box.w, box.y],
   [box.x, box.y + box.h], [box.x + box.w, box.y + box.h]]
    .every(([px, py]) => mask(px, py));
Enter fullscreen mode Exit fullscreen mode

Sampling four corners is cheap but lets a long word clip the edge. Sampling a grid of points inside the box is slower and much cleaner. Either way, add !insideMask(box, mask) to the rejection conditions in layout() and you have a shape cloud.

Here's what that ends up looking like — different sizes, rotations, and colors packed into a silhouette:

A shape-based word cloud with rotated, multi-colored words

The image above links to a live generator — handy if you want to try a shape mask without writing one.

5. Export

  • SVG: keep words as <text> elements. Infinite zoom, tiny files, editable in any vector tool.
  • PNG / JPG: draw the same layout to canvas and toBlob() at 2x for retina.
  • GIF / MP4: animate one property (rotation, opacity, or a per-word phase offset) and capture frames. Render at a fixed frame rate; don't rely on requestAnimationFrame timing for export.

Keeping layout and rendering separate is what makes all four formats nearly free once step 3 works.

When you shouldn't build this

If the goal is a slide deck due in ten minutes, the ~80 lines above are the wrong investment. Wordcloud.art is a browser tool that handles the shape masks, palettes, animation, and SVG/PNG/GIF/MP4 exports for you — paste text, pick a template, export.

The code is still the part I found worth understanding: once you see a word cloud as rectangle packing, a surprising number of other layout problems start to look the same.


Disclosure: I work on Wordcloud.art. The layout code above is generic, has no dependency on the tool, and runs in any browser.

Top comments (0)