Menu

Word Cloud Layout in JavaScript: Weighting, Spiral Packing, and Shape Masks
πŸ“°

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

DEV Community: datascienceΒ·YananLeeΒ·8 days ago
#9UL5de4q
#devtodatascience#science#devto#dev#const
Long article (1369 words) β€” no AI summary yet.
Reading 0:00
15s threshold

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) ??…

Continue reading β€” create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.