06Word Bubbles That Push Into Place
Words sit in round bubbles whose area tracks their counts and inflate one by one, trading a pull toward the center and a push equal to their overlap every 16 ms, until the jostling bubbles settle into a tight cluster.
Best forTrending keyword ranking board
PULLPUSHRELAX_PASSES

<main class="stage">
<div class="wc is-demo" id="wc">
<canvas class="wc__canvas" data-role="canvas" width="480" height="300" role="img" aria-label="Round bubbles holding words push each other apart as they gather toward the center."></canvas>
<ol class="wc__list" data-role="list" aria-label="Words ranked by frequency"></ol>
</div>
</main>@use "../../../../site/static/demo-tokens" as *;
@include stage($stage-ink);
.wc {
position: relative;
width: min(92vw, calc(160vh - 12.8vw));
aspect-ratio: 480 / 300;
margin: 0 auto;
border-radius: $r-card;
overflow: hidden;
box-shadow: $shadow-raised;
background: $subject-ink;
}
.wc__canvas {
position: absolute;
inset: 0;
display: block;
width: 100%;
height: 100%;
}
// 화면에서는 숨기고 화면 낭독기는 읽는 빈도 순 목록·알림 줄 — display: none 이 아니라 1px 상자로 줄여 접근성 트리에 남긴다
.wc__list,
.wc__live {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
border: 0;
}
.wc__vote {
position: absolute;
right: $sp-3;
bottom: $sp-3;
padding: $sp-1 $sp-3;
border: 0;
border-radius: $r-pill;
background: $subject-cream;
color: $subject-ink;
font-family: inherit;
font-weight: 700;
font-size: 12px;
line-height: 1.6;
cursor: pointer;
box-shadow: $shadow-press;
transition: transform $dur-quick $ease-spring;
}
.wc__vote:hover {
transform: translateY(-2px);
}
.wc__vote:active {
transform: translateY(1px);
}
.wc__vote:focus-visible {
outline: 2px solid $subject-cream;
outline-offset: 2px;
}
@media (max-width: 340px) {
.wc__vote { font-size: 11px; padding: $sp-1 $sp-2; }
}
// 동작 줄이기 — 장면은 스크립트가 마지막 배치 한 장면으로 멈춘다. 버튼도 떠오르지 않게
@media (prefers-reduced-motion: reduce) {
.wc__vote { transition: none !important; }
.wc__vote:hover,
.wc__vote:active { transform: none !important; }
}html, body {
margin: 0;
overflow: hidden;
}
.stage {
box-sizing: border-box;
min-height: 100vh;
display: grid;
place-items: center;
margin: 0;
background: #17141a;
font-family: -apple-system, "Segoe UI", "Noto Sans KR", sans-serif;
padding: clamp(8px, 4vw, 24px);
}
.wc {
position: relative;
width: min(92vw, 160vh - 12.8vw);
aspect-ratio: 480/300;
margin: 0 auto;
border-radius: 16px;
overflow: hidden;
box-shadow: 0 14px 24px rgba(23, 20, 26, 0.32);
background: #17141a;
}
.wc__canvas {
position: absolute;
inset: 0;
display: block;
width: 100%;
height: 100%;
}
.wc__list,
.wc__live {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
border: 0;
}
.wc__vote {
position: absolute;
right: 12px;
bottom: 12px;
padding: 4px 12px;
border: 0;
border-radius: 999px;
background: #fff7e6;
color: #17141a;
font-family: inherit;
font-weight: 700;
font-size: 12px;
line-height: 1.6;
cursor: pointer;
box-shadow: 0 6px 12px rgba(23, 20, 26, 0.32);
transition: transform 220ms cubic-bezier(0.2, 0.8, 0.2, 1);
}
.wc__vote:hover {
transform: translateY(-2px);
}
.wc__vote:active {
transform: translateY(1px);
}
.wc__vote:focus-visible {
outline: 2px solid #fff7e6;
outline-offset: 2px;
}
@media (max-width: 340px) {
.wc__vote {
font-size: 11px;
padding: 4px 8px;
}
}
@media (prefers-reduced-motion: reduce) {
.wc__vote {
transition: none !important;
}
.wc__vote:hover,
.wc__vote:active {
transform: none !important;
}
}(function () {
const root = document.getElementById("wc");
if (!root) return;
const W = 480;
const H = 300;
const FIXED_DT = 16;
const TAU = Math.PI * 2;
// 파스텔 팔레트 — 어두운 판 위에 밝은 파스텔 글자를 얹어 명도 차로 글자가 읽힌다
const BG = [30, 27, 44];
const BG_LOW = [44, 38, 64];
const GUIDE = [104, 96, 140];
const CREAM = [255, 248, 234];
const PEACH = [255, 204, 168];
const MINT = [140, 228, 196];
const SKY = [140, 204, 255];
const LEMON = [246, 230, 148];
const LILAC = [198, 176, 255];
const PINK = [255, 170, 198];
const WORD_COLORS = [PEACH, MINT, SKY, LEMON, LILAC, PINK];
// 글꼴 — 기기에 이미 있는 시스템 글꼴 목록만. 바깥에서 글꼴 파일을 불러오지 않는다
const FONT_FAMILY = '"Segoe UI", "Malgun Gothic", "Hiragino Sans", "Noto Sans KR", sans-serif';
const FONT_WEIGHT = 700;
// 크기 = SIZE_MAX × (횟수 / 1위 횟수)^SIZE_EXPONENT. 0.5(제곱근)면 글자 넓이(크기의 제곱)가 횟수에 비례한다
const SIZE_EXPONENT = 0.5;
const SIZE_MAX = 50;
const SIZE_MIN = 10;
function sizeFor(count, top) {
return Math.max(SIZE_MIN, SIZE_MAX * Math.pow(count / top, SIZE_EXPONENT));
}
// meetings·설문에서 흔히 나오는 낱말과 횟수 — 많이 나온 순. theme 은 0 Pace · 1 Together · 2 How we work · 3 Growing
const VOCAB = [
{ text: 'collaboration', count: 24, theme: 1 },
{ text: 'communication', count: 19, theme: 1 },
{ text: 'deadline', count: 16, theme: 0 },
{ text: 'feedback', count: 14, theme: 2 },
{ text: 'schedule', count: 12, theme: 0 },
{ text: 'growth', count: 11, theme: 3 },
{ text: 'sharing', count: 10, theme: 2 },
{ text: 'trust', count: 9, theme: 1 },
{ text: 'meetings', count: 8, theme: 0 },
{ text: 'priorities', count: 8, theme: 0 },
{ text: 'rest', count: 7, theme: 3 },
{ text: 'goals', count: 7, theme: 0 },
{ text: 'kindness', count: 6, theme: 1 },
{ text: 'docs', count: 6, theme: 2 },
{ text: 'praise', count: 6, theme: 1 },
{ text: 'focus', count: 5, theme: 0 },
{ text: 'automation', count: 5, theme: 2 },
{ text: 'learning', count: 5, theme: 3 },
{ text: 'reviews', count: 4, theme: 2 },
{ text: 'cheering', count: 4, theme: 1 },
{ text: 'challenge', count: 4, theme: 3 },
{ text: 'planning', count: 4, theme: 0 },
{ text: 'questions', count: 3, theme: 2 },
{ text: 'balance', count: 3, theme: 3 },
{ text: 'thanks', count: 3, theme: 1 },
{ text: 'speed', count: 3, theme: 0 },
{ text: 'data', count: 3, theme: 2 },
{ text: 'leeway', count: 3, theme: 3 },
{ text: 'retros', count: 2, theme: 0 },
{ text: 'support', count: 2, theme: 1 },
{ text: 'experiments', count: 2, theme: 2 },
{ text: 'habits', count: 2, theme: 3 },
{ text: 'quality', count: 2, theme: 2 },
{ text: 'mood', count: 2, theme: 1 },
{ text: 'change', count: 2, theme: 3 },
{ text: 'launch', count: 2, theme: 0 },
{ text: 'cleanup', count: 1, theme: 2 },
{ text: 'roles', count: 1, theme: 1 },
{ text: 'fun', count: 1, theme: 1 },
{ text: 'notes', count: 1, theme: 0 },
{ text: 'efficiency', count: 1, theme: 0 },
{ text: 'onboarding', count: 1, theme: 2 },
{ text: 'connection', count: 1, theme: 1 },
{ text: 'ideas', count: 1, theme: 3 },
{ text: 'stability', count: 1, theme: 3 },
{ text: 'transparency', count: 1, theme: 2 },
{ text: 'customers', count: 1, theme: 2 },
{ text: 'practice', count: 1, theme: 3 }
];
// 횟수 문구 — 1 은 따로 둔다(영어판의 단수형 자리)
const COUNT_LABEL = '{n} mentions';
const COUNT_ONE = '1 mention';
const TOP_LABEL = 'Most frequent:';
// 캔버스 요약에서 1~3위 앞에 붙는 말 — 09 투표판은 자기 말로 바꾼다
let rankHeading = TOP_LABEL;
function countText(n) { return n === 1 ? COUNT_ONE : COUNT_LABEL.replace('{n}', String(n)); }
function clamp(v, lo, hi) { return v < lo ? lo : (v > hi ? hi : v); }
function lerp(a, b, k) { return a + (b - a) * k; }
function smooth(x) { const c = clamp(x, 0, 1); return c * c * (3 - 2 * c); }
function rgba(c, a) {
return 'rgba(' + Math.round(clamp(c[0], 0, 255)) + ',' + Math.round(clamp(c[1], 0, 255)) + ',' + Math.round(clamp(c[2], 0, 255)) + ',' + clamp(a, 0, 1).toFixed(3) + ')';
}
function mixRGB(a, b, k) { return [lerp(a[0], b[0], k), lerp(a[1], b[1], k), lerp(a[2], b[2], k)]; }
// 시드 고정 난수 — 같은 시드면 같은 배치·일정표가 다시 나온다 (32비트 정수 섞기)
function makeRng(seed) {
let s = seed >>> 0;
return function () {
s = (s + 0x6d2b79f5) >>> 0;
let t = s;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
// 튀어나오기 — 감쇠 진동 1 − e^(−POP_DAMP·t)·cos(POP_FREQ·t), t 는 초. goals 크기를 한 번 넘겼다가 자리 잡는다
const POP_DAMP = 7;
const POP_FREQ = 11;
function popScale(t) {
if (t <= 0) {
return 0;
}
return 1 - Math.exp(-POP_DAMP * t) * Math.cos(POP_FREQ * t);
}
const canvasEl = root.querySelector('[data-role="canvas"]');
const listEl = root.querySelector('[data-role="list"]');
const ctxRaw = canvasEl ? canvasEl.getContext('2d') : null;
if (!canvasEl || !ctxRaw || !listEl) {
return;
}
const cv = canvasEl;
const ctx = ctxRaw;
const list = listEl;
// 캔버스 요약 — HTML 에 적힌 장면 설명 뒤에 지금 1~3위를 덧붙인다
const baseAria = cv.getAttribute('aria-label') || '';
const reduceQuery = window.matchMedia('(prefers-reduced-motion: reduce)');
// 페이지를 연 채 동작 줄이기 설정을 바꿔도 change 리스너가 이 값을 다시 읽는다
let still = reduceQuery.matches;
// 자동 시연 중인가 — 사람이 처음 손대면 시연 표시를 뗀다
let demo = root.classList.contains('is-demo');
// 리스너는 한 묶음으로 달고 정리할 때 한 번에 뗀다
const off = new AbortController();
// 포인터 자리(판 좌표) — 판 밖이면 -1
let hoverX = -1;
let hoverY = -1;
function fitCanvas() {
// 배율은 2 에서 자른다 — 배율 3 기기에서 화소가 2.25배로 늘어 프레임마다 일이 그만큼 커지지 않게
const dpr = Math.min(window.devicePixelRatio || 1, 2);
cv.width = Math.round(W * dpr);
cv.height = Math.round(H * dpr);
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
}
function clearStage() {
const g = ctx.createLinearGradient(0, 0, 0, H);
g.addColorStop(0, rgba(BG, 1));
g.addColorStop(1, rgba(BG_LOW, 1));
ctx.fillStyle = g;
ctx.fillRect(0, 0, W, H);
}
function fontOf(size) { return FONT_WEIGHT + ' ' + size.toFixed(1) + 'px ' + FONT_FAMILY; }
function roundRectPath(x, y, w, h, r) {
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.arcTo(x + w, y, x + w, y + h, r);
ctx.arcTo(x + w, y + h, x, y + h, r);
ctx.arcTo(x, y + h, x, y, r);
ctx.arcTo(x, y, x + w, y, r);
ctx.closePath();
}
// 놓인 낱말 그리기 — 상자 가운데를 중심으로 scale 배·angle 라디안 돌리고 lift 만큼 띄운다. 비트 칸을 만든 자리와 같은 기준선에 찍는다
function drawPlaced(p, alpha, scale, angle, lift, color) {
if (alpha <= 0.002 || scale <= 0.001) {
return;
}
const cx = p.x + p.w / 2;
const cy = p.y + p.h / 2;
ctx.save();
ctx.translate(cx, cy - lift);
if (angle !== 0) {
ctx.rotate(angle);
}
if (scale !== 1) {
ctx.scale(scale, scale);
}
ctx.font = fontOf(p.size);
ctx.textAlign = 'left';
ctx.textBaseline = 'alphabetic';
ctx.fillStyle = rgba(color, alpha);
ctx.fillText(p.text, p.x + p.dx - cx, p.y + p.dy - cy);
ctx.restore();
}
function hitPlaced(p) {
return hoverX >= p.x && hoverX <= p.x + p.w && hoverY >= p.y && hoverY <= p.y + p.h;
}
// 포인터 아래 낱말 — 뒤에 그린 것이 위에 있으니 뒤에서부터 찾는다. shown(i) 가 거짓인 낱말은 건너뛴다
function pickPlaced(ps, shown) {
if (hoverX < 0) {
return -1;
}
for (let i = ps.length - 1; i >= 0; i -= 1) {
if (shown(i) && hitPlaced(ps[i])) {
return i;
}
}
return -1;
}
function drawHalo(x, y, w, h) {
ctx.lineWidth = 1.5;
ctx.strokeStyle = rgba(CREAM, 0.9);
roundRectPath(x - 3, y - 2, w + 6, h + 4, 6);
ctx.stroke();
}
// 말풍선 — 낱말과 횟수를 크림 바탕에 진한 글자로
function drawTip(label, ax, ay) {
ctx.font = fontOf(11);
const bw = ctx.measureText(label).width + 16;
const bh = 22;
const bx = clamp(ax - bw / 2, 4, W - bw - 4);
const by = ay - bh - 8 < 4 ? ay + 10 : ay - bh - 8;
ctx.fillStyle = rgba(CREAM, 0.96);
roundRectPath(bx, by, bw, bh, 8);
ctx.fill();
ctx.fillStyle = rgba(BG, 1);
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(label, bx + bw / 2, by + bh / 2 + 0.5);
}
// 판 위 설명 글 — 어두운 알약 바탕에 작은 크림 글자. 돌려주는 값은 차지한 상자 [x, y, w, h]
function drawCaption(text, x, y, alignRight) {
ctx.font = fontOf(11);
const bw = ctx.measureText(text).width + 14;
const bh = 20;
const bx = alignRight ? x - bw : x;
ctx.fillStyle = rgba(BG, 0.82);
roundRectPath(bx, y, bw, bh, 8);
ctx.fill();
ctx.fillStyle = rgba(CREAM, 0.92);
ctx.textAlign = 'left';
ctx.textBaseline = 'middle';
ctx.fillText(text, bx + 7, y + bh / 2 + 0.5);
return [bx, y, bw, bh];
}
const BUBBLE_COUNT = 22;
const BUBBLE_MAX_R = 50;
const BUBBLE_MIN_R = 14;
// 가운데 끌기 — 틱마다 가운데까지 거리의 PULL 배를 속도에 더한다(세로는 PULL_Y 배 더 세게 — 판이 가로로 넓어서)
const PULL = 0.0011;
const PULL_Y = 1.8;
// 겹친 만큼 밀어내기 — 두 거품이 BUBBLE_GAP 보다 가까우면 모자란 거리의 PUSH 배를 둘이 나눠 비킨다(작은 쪽이 더 많이). RELAX_PASSES 번 되풀이
const PUSH = 0.45;
const RELAX_PASSES = 3;
const BUBBLE_GAP = 3;
const DAMPING = 0.9;
// 맞닿음 감쇠 — 겹친 거리 합(px) 1 마다 속도를 1 / (1 + CONTACT_DAMP) 배로
const CONTACT_DAMP = 0.5;
// 시작 — 가운데 둘레 START_SPREAD px 안에 시드 고정으로 모아 두고, START_MS 부터 GROW_GAP_MS 간격으로 하나씩 GROW_MS 동안 부풀린다.
// 부푼 거품이 이웃을 밀어내며 자리를 찾고, KICK_MS 에 바깥으로 한 번 튕겨 다시 모인다
const SCATTER_SEED = 4776;
const START_SPREAD = 70;
const START_MS = 200;
const GROW_GAP_MS = 60;
const GROW_MS = 500;
const KICK_MS = 3000;
const KICK = 6;
const LOOP_MS = 6000;
const SETTLE_TICKS = 600;
let bubbles = [];
let fresh = true;
let lastT = -1;
// 지금 겹친 거리의 합(px) — 첫 되풀이에서 잰다. 0 에 가까울수록 다 비켜선 것
let overlapSum = 0;
function build() {
const top = VOCAB[0].count;
bubbles = [];
for (let i = 0; i < Math.min(BUBBLE_COUNT, VOCAB.length); i += 1) {
const e = VOCAB[i];
const r = Math.max(BUBBLE_MIN_R, BUBBLE_MAX_R * Math.sqrt(e.count / top));
// 글자 크기 — 20px 로 잰 폭을 거품 지름의 78% 에 맞추고, 반지름의 0.62 배를 넘지 않게
ctx.font = fontOf(20);
const m = ctx.measureText(e.text);
const size = Math.min(r * 0.62, (2 * r * 0.78) / Math.max(1, m.width) * 20);
ctx.font = fontOf(size);
const mm = ctx.measureText(e.text);
bubbles.push({ e: e, r: r, size: size, base: (mm.actualBoundingBoxAscent - mm.actualBoundingBoxDescent) / 2, x: 0, y: 0, vx: 0, vy: 0, color: WORD_COLORS[i % WORD_COLORS.length], press: 0, grow: 0 });
}
fresh = true;
}
function scatter() {
const rng = makeRng(SCATTER_SEED);
for (let i = 0; i < bubbles.length; i += 1) {
const b = bubbles[i];
const a = rng() * TAU;
const d = rng() * START_SPREAD;
b.x = W / 2 + Math.cos(a) * d * 1.6;
b.y = H / 2 + Math.sin(a) * d;
b.vx = 0;
b.vy = 0;
b.grow = 0;
}
}
function kick() {
for (let i = 0; i < bubbles.length; i += 1) {
const b = bubbles[i];
const dx = b.x - W / 2;
const dy = b.y - H / 2;
const d = Math.hypot(dx, dy) || 1;
b.vx += dx / d * KICK;
b.vy += dy / d * KICK;
}
}
function physicsTick() {
for (let i = 0; i < bubbles.length; i += 1) {
const b = bubbles[i];
b.vx = (b.vx + (W / 2 - b.x) * PULL) * DAMPING;
b.vy = (b.vy + (H / 2 - b.y) * PULL * PULL_Y) * DAMPING;
b.x += b.vx;
b.y += b.vy;
b.press = 0;
}
overlapSum = 0;
for (let pass = 0; pass < RELAX_PASSES; pass += 1) {
for (let i = 0; i < bubbles.length; i += 1) {
for (let j = i + 1; j < bubbles.length; j += 1) {
const a = bubbles[i];
const b = bubbles[j];
const ra = a.r * a.grow;
const rb = b.r * b.grow;
if (ra <= 0 || rb <= 0) {
continue;
}
const dx = b.x - a.x;
const dy = b.y - a.y;
const d = Math.hypot(dx, dy) || 0.01;
const gap = ra + rb + BUBBLE_GAP - d;
if (gap <= 0) {
continue;
}
if (pass === 0) {
overlapSum += gap;
a.press += gap;
b.press += gap;
}
const nx = dx / d;
const ny = dy / d;
// 작은 거품이 더 많이 비킨다 — 내 몫 = 상대 넓이 / 둘의 넓이 합
const share = (rb * rb) / (ra * ra + rb * rb);
a.x -= nx * gap * PUSH * share;
a.y -= ny * gap * PUSH * share;
b.x += nx * gap * PUSH * (1 - share);
b.y += ny * gap * PUSH * (1 - share);
}
}
}
// 판 벽 — 넘으면 벽에 붙이고 그 방향 속도를 없앤다. 눌린 거품은 눌린 만큼 속도를 잃는다(맞닿은 면이 힘을 받아 준다)
for (let i = 0; i < bubbles.length; i += 1) {
const b = bubbles[i];
const r = b.r * b.grow;
const hold = 1 / (1 + b.press * CONTACT_DAMP);
b.vx *= hold;
b.vy *= hold;
if (b.x < r) {
b.x = r;
b.vx = 0;
}
if (b.x > W - r) {
b.x = W - r;
b.vx = 0;
}
if (b.y < r) {
b.y = r;
b.vy = 0;
}
if (b.y > H - r) {
b.y = H - r;
b.vy = 0;
}
}
}
function loopLength() { return LOOP_MS; }
function step(ms) {
if (fresh) {
scatter();
fresh = false;
lastT = -1;
}
if (lastT >= 0 && lastT < KICK_MS && ms >= KICK_MS) {
kick();
}
lastT = ms;
for (let i = 0; i < bubbles.length; i += 1) {
bubbles[i].grow = Math.max(bubbles[i].grow, smooth((ms - START_MS - i * GROW_GAP_MS) / GROW_MS));
}
if (ms >= START_MS) {
physicsTick();
}
}
// 동작 줄이기 — 다 부푼 거품으로 SETTLE_TICKS 번 이완을 그리지 않고 한 번에 돌린 뒤 가라앉은 덩어리 한 장면
function finalScene() {
scatter();
for (let i = 0; i < bubbles.length; i += 1) {
bubbles[i].grow = 1;
}
for (let k = 0; k < SETTLE_TICKS; k += 1) {
physicsTick();
}
fresh = false;
}
function onWake() { }
function hitBubble(b) { return hoverX >= 0 && Math.hypot(hoverX - b.x, hoverY - b.y) <= b.r * b.grow; }
function draw() {
clearStage();
let hi = -1;
for (let i = bubbles.length - 1; i >= 0; i -= 1) {
if (hitBubble(bubbles[i])) {
hi = i;
break;
}
}
for (let i = 0; i < bubbles.length; i += 1) {
const b = bubbles[i];
if (b.grow <= 0.01) {
continue;
}
const k = (i === hi ? 1.06 : 1) * b.grow;
const r = b.r * k;
// 거품 — 왼쪽 위가 밝은 원형 그라디언트(빛이 위에서 온다)
const g = ctx.createRadialGradient(b.x - r * 0.35, b.y - r * 0.4, r * 0.1, b.x, b.y, r);
g.addColorStop(0, rgba(mixRGB(b.color, CREAM, 0.55), 0.96));
g.addColorStop(1, rgba(b.color, 0.92));
ctx.fillStyle = g;
ctx.beginPath();
ctx.arc(b.x, b.y, r, 0, TAU);
ctx.fill();
// 눌린 만큼 테두리 — 겹친 거리가 클수록 진한 분홍 고리
if (b.press > 0.3) {
ctx.lineWidth = 2.5;
ctx.strokeStyle = rgba(PINK, clamp(b.press / 14, 0, 1));
ctx.beginPath();
ctx.arc(b.x, b.y, r + 1.5, 0, TAU);
ctx.stroke();
}
ctx.font = fontOf(b.size * k);
ctx.textAlign = 'center';
ctx.textBaseline = 'alphabetic';
ctx.fillStyle = rgba(BG, 1);
ctx.fillText(b.e.text, b.x, b.y + b.base * k);
}
if (hi >= 0) {
const b = bubbles[hi];
drawTip(b.e.text + ' · ' + countText(b.e.count), b.x, b.y - b.r * b.grow);
}
}
function ranking() {
return bubbles.map(function (b) { return [b.e.text, b.e.count, countText(b.e.count)]; });
}
// 글꼴 준비가 끝나 배치를 계산했는가
let ready = false;
// cleanup 뒤(리액트 언마운트)에 늦게 온 글꼴 준비 알림이 일을 시작하지 않게
let alive = true;
// 시연 시계(ms) — 16ms 고정 스텝으로만 늘어난다
let clock = 0;
function wake() {
if (!demo) {
return;
}
demo = false;
root.classList.remove('is-demo');
onWake();
}
// 포인터 자리를 판 좌표(480×300)로 — 화면에 보이는 캔버스 크기와 상관없이
function toBoard(ev) {
const r = cv.getBoundingClientRect();
return [(ev.clientX - r.left) * W / Math.max(1, r.width), (ev.clientY - r.top) * H / Math.max(1, r.height)];
}
cv.addEventListener('pointermove', function (ev) {
const p = toBoard(ev);
hoverX = p[0];
hoverY = p[1];
wake();
if (still && ready) {
render();
}
}, { signal: off.signal });
cv.addEventListener('pointerleave', function () {
hoverX = -1;
hoverY = -1;
if (still && ready) {
render();
}
}, { signal: off.signal });
// 숨긴 목록 — 순위나 횟수가 바뀐 때만 다시 쓴다. 캔버스 요약에는 1~3위를 붙인다
let listKey = '';
function syncList() {
const rows = ranking();
const key = rows.map(function (r) { return r[0] + ':' + r[1]; }).join('|');
if (key === listKey) {
return;
}
listKey = key;
while (list.firstChild) {
list.removeChild(list.firstChild);
}
for (let i = 0; i < rows.length; i += 1) {
const li = document.createElement('li');
li.textContent = rows[i][0] + ' — ' + rows[i][2];
list.appendChild(li);
}
const top = rows.slice(0, 3).map(function (r) { return r[0] + ' ' + r[2]; }).join(', ');
cv.setAttribute('aria-label', baseAria + ' ' + rankHeading + ' ' + top);
}
function render() {
draw();
syncList();
}
let rafId = 0;
let lastTs = -1;
let acc = 0;
function frame(ts) {
if (still) {
rafId = 0;
return;
}
if (lastTs < 0) {
lastTs = ts;
}
// 탭이 숨었다 돌아와도 한 번에 100ms 까지만 따라잡는다
acc += Math.min(ts - lastTs, 100);
lastTs = ts;
let n = 0;
while (acc >= FIXED_DT && n < 6) {
clock += FIXED_DT;
step(clock % loopLength());
acc -= FIXED_DT;
n += 1;
}
render();
rafId = window.requestAnimationFrame(frame);
}
function startLoop() {
if (rafId) {
return;
}
lastTs = -1;
acc = 0;
rafId = window.requestAnimationFrame(frame);
}
function stopLoop() {
if (rafId) {
window.cancelAnimationFrame(rafId);
rafId = 0;
}
}
// 동작 줄이기 — 루프를 돌리지 않고 배치를 끝까지 계산한 마지막 한 장면만 그린다
function showStill() {
stopLoop();
finalScene();
render();
}
function play() {
clock = 0;
step(0);
render();
startLoop();
}
// 설정이 페이지를 연 채 바뀌면 — 켜지면 마지막 장면에서 멈추고, 꺼지면 시연을 처음부터
function onMotionPref() {
still = reduceQuery.matches;
if (!ready) {
return;
}
if (still) {
showStill();
}
else {
play();
}
}
reduceQuery.addEventListener('change', onMotionPref, { signal: off.signal });
window.addEventListener('resize', function () {
fitCanvas();
if (ready) {
render();
}
}, { signal: off.signal });
function begin() {
if (!alive) {
return;
}
fitCanvas();
build();
ready = true;
if (still) {
showStill();
}
else {
play();
}
}
// 글꼴 — 준비(document.fonts.ready)가 끝난 뒤에 글자 폭을 잰다. 준비 전에 재면 나중에 바뀐 글꼴과 비트 칸이 어긋난다
const fontSet = document.fonts;
// 늦게 도착한 글꼴 — 배치를 마친 뒤 글꼴이 새로 들어오면 글자 폭을 다시 재 배치를 다시 계산한다
fontSet.addEventListener('loadingdone', function () {
if (!ready || !alive) {
return;
}
build();
if (still) {
finalScene();
}
render();
}, { signal: off.signal });
fontSet.ready.then(begin);
return function () {
alive = false;
stopLoop();
off.abort();
};
})();// BubbleForceRelaxPack - vanilla 판(06-wc-bubble-force-relax-pack) 의 React 포트. 같은 계산을 useEffect 안에서 돌린다.
import { useEffect, useRef } from "react";
import styles from "./BubbleForceRelaxPack.module.scss";
const cx = (s: string): string => s.split(" ").map((n) => styles[n] ?? n).join(" ");
export default function BubbleForceRelaxPack() {
const rootRef = useRef<HTMLDivElement | null>(null);
useEffect(() => {
const rootEl = rootRef.current;
if (!rootEl) return;
const root: HTMLElement = rootEl;
type RGB = [number, number, number];
type Pt = [number, number];
// 낱말 하나 — 글자, 나온 횟수, 주제 번호(05 무리 색)
type Entry = { text: string; count: number; theme: number };
// 판에 놓인 낱말 — (x, y) 는 글자 상자 왼쪽 위, w·h 는 상자 크기, (dx, dy) 는 상자 왼쪽 위에서 글자 기준선 시작점까지
type Placed = { text: string; count: number; theme: number; size: number; x: number; y: number; w: number; h: number; dx: number; dy: number; color: RGB; shrinks: number };
// 숨긴 목록 한 줄 — 낱말, 횟수, 읽어 줄 횟수 문구
type Row = [string, number, string];
const W = 480;
const H = 300;
const FIXED_DT = 16;
const TAU = Math.PI * 2;
// 파스텔 팔레트 — 어두운 판 위에 밝은 파스텔 글자를 얹어 명도 차로 글자가 읽힌다
const BG: RGB = [30, 27, 44];
const BG_LOW: RGB = [44, 38, 64];
const GUIDE: RGB = [104, 96, 140];
const CREAM: RGB = [255, 248, 234];
const PEACH: RGB = [255, 204, 168];
const MINT: RGB = [140, 228, 196];
const SKY: RGB = [140, 204, 255];
const LEMON: RGB = [246, 230, 148];
const LILAC: RGB = [198, 176, 255];
const PINK: RGB = [255, 170, 198];
const WORD_COLORS: RGB[] = [PEACH, MINT, SKY, LEMON, LILAC, PINK];
// 글꼴 — 기기에 이미 있는 시스템 글꼴 목록만. 바깥에서 글꼴 파일을 불러오지 않는다
const FONT_FAMILY = '"Segoe UI", "Malgun Gothic", "Hiragino Sans", "Noto Sans KR", sans-serif';
const FONT_WEIGHT = 700;
// 크기 = SIZE_MAX × (횟수 / 1위 횟수)^SIZE_EXPONENT. 0.5(제곱근)면 글자 넓이(크기의 제곱)가 횟수에 비례한다
const SIZE_EXPONENT = 0.5;
const SIZE_MAX = 50;
const SIZE_MIN = 10;
function sizeFor(count: number, top: number): number {
return Math.max(SIZE_MIN, SIZE_MAX * Math.pow(count / top, SIZE_EXPONENT));
}
// 회의·설문에서 흔히 나오는 낱말과 횟수 — 많이 나온 순. theme 은 0 일의 속도 · 1 함께하기 · 2 일하는 방식 · 3 배우고 자라기
const VOCAB: Entry[] = [
{ text: '협업', count: 24, theme: 1 },
{ text: '소통', count: 19, theme: 1 },
{ text: '마감', count: 16, theme: 0 },
{ text: '피드백', count: 14, theme: 2 },
{ text: '일정', count: 12, theme: 0 },
{ text: '성장', count: 11, theme: 3 },
{ text: '공유', count: 10, theme: 2 },
{ text: '신뢰', count: 9, theme: 1 },
{ text: '회의', count: 8, theme: 0 },
{ text: '우선순위', count: 8, theme: 0 },
{ text: '휴식', count: 7, theme: 3 },
{ text: '목표', count: 7, theme: 0 },
{ text: '배려', count: 6, theme: 1 },
{ text: '문서', count: 6, theme: 2 },
{ text: '칭찬', count: 6, theme: 1 },
{ text: '집중', count: 5, theme: 0 },
{ text: '자동화', count: 5, theme: 2 },
{ text: '학습', count: 5, theme: 3 },
{ text: '리뷰', count: 4, theme: 2 },
{ text: '응원', count: 4, theme: 1 },
{ text: '도전', count: 4, theme: 3 },
{ text: '계획', count: 4, theme: 0 },
{ text: '질문', count: 3, theme: 2 },
{ text: '균형', count: 3, theme: 3 },
{ text: '감사', count: 3, theme: 1 },
{ text: '속도', count: 3, theme: 0 },
{ text: '데이터', count: 3, theme: 2 },
{ text: '여유', count: 3, theme: 3 },
{ text: '회고', count: 2, theme: 0 },
{ text: '지원', count: 2, theme: 1 },
{ text: '실험', count: 2, theme: 2 },
{ text: '습관', count: 2, theme: 3 },
{ text: '품질', count: 2, theme: 2 },
{ text: '분위기', count: 2, theme: 1 },
{ text: '변화', count: 2, theme: 3 },
{ text: '출시', count: 2, theme: 0 },
{ text: '정리', count: 1, theme: 2 },
{ text: '역할', count: 1, theme: 1 },
{ text: '재미', count: 1, theme: 1 },
{ text: '기록', count: 1, theme: 0 },
{ text: '효율', count: 1, theme: 0 },
{ text: '온보딩', count: 1, theme: 2 },
{ text: '연결', count: 1, theme: 1 },
{ text: '아이디어', count: 1, theme: 3 },
{ text: '안정', count: 1, theme: 3 },
{ text: '투명성', count: 1, theme: 2 },
{ text: '고객', count: 1, theme: 2 },
{ text: '연습', count: 1, theme: 3 }
];
// 횟수 문구 — 1 은 따로 둔다(영어판의 단수형 자리)
const COUNT_LABEL = '{n}회';
const COUNT_ONE = '1회';
const TOP_LABEL = '가장 많이 나온 말:';
// 캔버스 요약에서 1~3위 앞에 붙는 말 — 09 투표판은 자기 말로 바꾼다
let rankHeading = TOP_LABEL;
function countText(n: number): string { return n === 1 ? COUNT_ONE : COUNT_LABEL.replace('{n}', String(n)); }
function clamp(v: number, lo: number, hi: number): number { return v < lo ? lo : (v > hi ? hi : v); }
function lerp(a: number, b: number, k: number): number { return a + (b - a) * k; }
function smooth(x: number): number { const c = clamp(x, 0, 1); return c * c * (3 - 2 * c); }
function rgba(c: RGB, a: number): string {
return 'rgba(' + Math.round(clamp(c[0], 0, 255)) + ',' + Math.round(clamp(c[1], 0, 255)) + ',' + Math.round(clamp(c[2], 0, 255)) + ',' + clamp(a, 0, 1).toFixed(3) + ')';
}
function mixRGB(a: RGB, b: RGB, k: number): RGB { return [lerp(a[0], b[0], k), lerp(a[1], b[1], k), lerp(a[2], b[2], k)]; }
// 시드 고정 난수 — 같은 시드면 같은 배치·일정표가 다시 나온다 (32비트 정수 섞기)
function makeRng(seed: number): () => number {
let s = seed >>> 0;
return function (): number {
s = (s + 0x6d2b79f5) >>> 0;
let t = s;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
// 튀어나오기 — 감쇠 진동 1 − e^(−POP_DAMP·t)·cos(POP_FREQ·t), t 는 초. 목표 크기를 한 번 넘겼다가 자리 잡는다
const POP_DAMP = 7;
const POP_FREQ = 11;
function popScale(t: number): number {
if (t <= 0) { return 0; }
return 1 - Math.exp(-POP_DAMP * t) * Math.cos(POP_FREQ * t);
}
const canvasEl = root.querySelector('[data-role="canvas"]') as HTMLCanvasElement | null;
const listEl = root.querySelector('[data-role="list"]') as HTMLElement | null;
const ctxRaw = canvasEl ? canvasEl.getContext('2d') : null;
if (!canvasEl || !ctxRaw || !listEl) { return; }
const cv: HTMLCanvasElement = canvasEl;
const ctx: CanvasRenderingContext2D = ctxRaw;
const list: HTMLElement = listEl;
// 캔버스 요약 — HTML 에 적힌 장면 설명 뒤에 지금 1~3위를 덧붙인다
const baseAria = cv.getAttribute('aria-label') || '';
const reduceQuery = window.matchMedia('(prefers-reduced-motion: reduce)');
// 페이지를 연 채 동작 줄이기 설정을 바꿔도 change 리스너가 이 값을 다시 읽는다
let still = reduceQuery.matches;
// 자동 시연 중인가 — 사람이 처음 손대면 시연 표시를 뗀다
let demo = root.classList.contains('is-demo');
// 리스너는 한 묶음으로 달고 정리할 때 한 번에 뗀다
const off = new AbortController();
// 포인터 자리(판 좌표) — 판 밖이면 -1
let hoverX = -1;
let hoverY = -1;
function fitCanvas(): void {
// 배율은 2 에서 자른다 — 배율 3 기기에서 화소가 2.25배로 늘어 프레임마다 일이 그만큼 커지지 않게
const dpr = Math.min(window.devicePixelRatio || 1, 2);
cv.width = Math.round(W * dpr);
cv.height = Math.round(H * dpr);
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
}
function clearStage(): void {
const g = ctx.createLinearGradient(0, 0, 0, H);
g.addColorStop(0, rgba(BG, 1));
g.addColorStop(1, rgba(BG_LOW, 1));
ctx.fillStyle = g;
ctx.fillRect(0, 0, W, H);
}
function fontOf(size: number): string { return FONT_WEIGHT + ' ' + size.toFixed(1) + 'px ' + FONT_FAMILY; }
function roundRectPath(x: number, y: number, w: number, h: number, r: number): void {
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.arcTo(x + w, y, x + w, y + h, r);
ctx.arcTo(x + w, y + h, x, y + h, r);
ctx.arcTo(x, y + h, x, y, r);
ctx.arcTo(x, y, x + w, y, r);
ctx.closePath();
}
// 놓인 낱말 그리기 — 상자 가운데를 중심으로 scale 배·angle 라디안 돌리고 lift 만큼 띄운다. 비트 칸을 만든 자리와 같은 기준선에 찍는다
function drawPlaced(p: Placed, alpha: number, scale: number, angle: number, lift: number, color: RGB): void {
if (alpha <= 0.002 || scale <= 0.001) { return; }
const cx = p.x + p.w / 2;
const cy = p.y + p.h / 2;
ctx.save();
ctx.translate(cx, cy - lift);
if (angle !== 0) { ctx.rotate(angle); }
if (scale !== 1) { ctx.scale(scale, scale); }
ctx.font = fontOf(p.size);
ctx.textAlign = 'left';
ctx.textBaseline = 'alphabetic';
ctx.fillStyle = rgba(color, alpha);
ctx.fillText(p.text, p.x + p.dx - cx, p.y + p.dy - cy);
ctx.restore();
}
function hitPlaced(p: Placed): boolean {
return hoverX >= p.x && hoverX <= p.x + p.w && hoverY >= p.y && hoverY <= p.y + p.h;
}
// 포인터 아래 낱말 — 뒤에 그린 것이 위에 있으니 뒤에서부터 찾는다. shown(i) 가 거짓인 낱말은 건너뛴다
function pickPlaced(ps: Placed[], shown: (i: number) => boolean): number {
if (hoverX < 0) { return -1; }
for (let i = ps.length - 1; i >= 0; i -= 1) {
if (shown(i) && hitPlaced(ps[i])) { return i; }
}
return -1;
}
function drawHalo(x: number, y: number, w: number, h: number): void {
ctx.lineWidth = 1.5;
ctx.strokeStyle = rgba(CREAM, 0.9);
roundRectPath(x - 3, y - 2, w + 6, h + 4, 6);
ctx.stroke();
}
// 말풍선 — 낱말과 횟수를 크림 바탕에 진한 글자로
function drawTip(label: string, ax: number, ay: number): void {
ctx.font = fontOf(11);
const bw = ctx.measureText(label).width + 16;
const bh = 22;
const bx = clamp(ax - bw / 2, 4, W - bw - 4);
const by = ay - bh - 8 < 4 ? ay + 10 : ay - bh - 8;
ctx.fillStyle = rgba(CREAM, 0.96);
roundRectPath(bx, by, bw, bh, 8);
ctx.fill();
ctx.fillStyle = rgba(BG, 1);
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(label, bx + bw / 2, by + bh / 2 + 0.5);
}
// 판 위 설명 글 — 어두운 알약 바탕에 작은 크림 글자. 돌려주는 값은 차지한 상자 [x, y, w, h]
function drawCaption(text: string, x: number, y: number, alignRight: boolean): [number, number, number, number] {
ctx.font = fontOf(11);
const bw = ctx.measureText(text).width + 14;
const bh = 20;
const bx = alignRight ? x - bw : x;
ctx.fillStyle = rgba(BG, 0.82);
roundRectPath(bx, y, bw, bh, 8);
ctx.fill();
ctx.fillStyle = rgba(CREAM, 0.92);
ctx.textAlign = 'left';
ctx.textBaseline = 'middle';
ctx.fillText(text, bx + 7, y + bh / 2 + 0.5);
return [bx, y, bw, bh];
}
// 거품 하나 — 반지름은 넓이가 횟수에 비례하게(√횟수), 글자는 거품 안에 들어가는 크기. grow 는 0~1 로 부풀어 오른 정도
type Bubble = { e: Entry; r: number; size: number; base: number; x: number; y: number; vx: number; vy: number; color: RGB; press: number; grow: number };
const BUBBLE_COUNT = 22;
const BUBBLE_MAX_R = 50;
const BUBBLE_MIN_R = 14;
// 가운데 끌기 — 틱마다 가운데까지 거리의 PULL 배를 속도에 더한다(세로는 PULL_Y 배 더 세게 — 판이 가로로 넓어서)
const PULL = 0.0011;
const PULL_Y = 1.8;
// 겹친 만큼 밀어내기 — 두 거품이 BUBBLE_GAP 보다 가까우면 모자란 거리의 PUSH 배를 둘이 나눠 비킨다(작은 쪽이 더 많이). RELAX_PASSES 번 되풀이
const PUSH = 0.45;
const RELAX_PASSES = 3;
const BUBBLE_GAP = 3;
const DAMPING = 0.9;
// 맞닿음 감쇠 — 겹친 거리 합(px) 1 마다 속도를 1 / (1 + CONTACT_DAMP) 배로
const CONTACT_DAMP = 0.5;
// 시작 — 가운데 둘레 START_SPREAD px 안에 시드 고정으로 모아 두고, START_MS 부터 GROW_GAP_MS 간격으로 하나씩 GROW_MS 동안 부풀린다.
// 부푼 거품이 이웃을 밀어내며 자리를 찾고, KICK_MS 에 바깥으로 한 번 튕겨 다시 모인다
const SCATTER_SEED = 4776;
const START_SPREAD = 70;
const START_MS = 200;
const GROW_GAP_MS = 60;
const GROW_MS = 500;
const KICK_MS = 3000;
const KICK = 6;
const LOOP_MS = 6000;
const SETTLE_TICKS = 600;
let bubbles: Bubble[] = [];
let fresh = true;
let lastT = -1;
// 지금 겹친 거리의 합(px) — 첫 되풀이에서 잰다. 0 에 가까울수록 다 비켜선 것
let overlapSum = 0;
function build(): void {
const top = VOCAB[0].count;
bubbles = [];
for (let i = 0; i < Math.min(BUBBLE_COUNT, VOCAB.length); i += 1) {
const e = VOCAB[i];
const r = Math.max(BUBBLE_MIN_R, BUBBLE_MAX_R * Math.sqrt(e.count / top));
// 글자 크기 — 20px 로 잰 폭을 거품 지름의 78% 에 맞추고, 반지름의 0.62 배를 넘지 않게
ctx.font = fontOf(20);
const m = ctx.measureText(e.text);
const size = Math.min(r * 0.62, (2 * r * 0.78) / Math.max(1, m.width) * 20);
ctx.font = fontOf(size);
const mm = ctx.measureText(e.text);
bubbles.push({ e: e, r: r, size: size, base: (mm.actualBoundingBoxAscent - mm.actualBoundingBoxDescent) / 2, x: 0, y: 0, vx: 0, vy: 0, color: WORD_COLORS[i % WORD_COLORS.length], press: 0, grow: 0 });
}
fresh = true;
}
function scatter(): void {
const rng = makeRng(SCATTER_SEED);
for (let i = 0; i < bubbles.length; i += 1) {
const b = bubbles[i];
const a = rng() * TAU;
const d = rng() * START_SPREAD;
b.x = W / 2 + Math.cos(a) * d * 1.6;
b.y = H / 2 + Math.sin(a) * d;
b.vx = 0;
b.vy = 0;
b.grow = 0;
}
}
function kick(): void {
for (let i = 0; i < bubbles.length; i += 1) {
const b = bubbles[i];
const dx = b.x - W / 2;
const dy = b.y - H / 2;
const d = Math.hypot(dx, dy) || 1;
b.vx += dx / d * KICK;
b.vy += dy / d * KICK;
}
}
function physicsTick(): void {
for (let i = 0; i < bubbles.length; i += 1) {
const b = bubbles[i];
b.vx = (b.vx + (W / 2 - b.x) * PULL) * DAMPING;
b.vy = (b.vy + (H / 2 - b.y) * PULL * PULL_Y) * DAMPING;
b.x += b.vx;
b.y += b.vy;
b.press = 0;
}
overlapSum = 0;
for (let pass = 0; pass < RELAX_PASSES; pass += 1) {
for (let i = 0; i < bubbles.length; i += 1) {
for (let j = i + 1; j < bubbles.length; j += 1) {
const a = bubbles[i];
const b = bubbles[j];
const ra = a.r * a.grow;
const rb = b.r * b.grow;
if (ra <= 0 || rb <= 0) { continue; }
const dx = b.x - a.x;
const dy = b.y - a.y;
const d = Math.hypot(dx, dy) || 0.01;
const gap = ra + rb + BUBBLE_GAP - d;
if (gap <= 0) { continue; }
if (pass === 0) { overlapSum += gap; a.press += gap; b.press += gap; }
const nx = dx / d;
const ny = dy / d;
// 작은 거품이 더 많이 비킨다 — 내 몫 = 상대 넓이 / 둘의 넓이 합
const share = (rb * rb) / (ra * ra + rb * rb);
a.x -= nx * gap * PUSH * share;
a.y -= ny * gap * PUSH * share;
b.x += nx * gap * PUSH * (1 - share);
b.y += ny * gap * PUSH * (1 - share);
}
}
}
// 판 벽 — 넘으면 벽에 붙이고 그 방향 속도를 없앤다. 눌린 거품은 눌린 만큼 속도를 잃는다(맞닿은 면이 힘을 받아 준다)
for (let i = 0; i < bubbles.length; i += 1) {
const b = bubbles[i];
const r = b.r * b.grow;
const hold = 1 / (1 + b.press * CONTACT_DAMP);
b.vx *= hold;
b.vy *= hold;
if (b.x < r) { b.x = r; b.vx = 0; }
if (b.x > W - r) { b.x = W - r; b.vx = 0; }
if (b.y < r) { b.y = r; b.vy = 0; }
if (b.y > H - r) { b.y = H - r; b.vy = 0; }
}
}
function loopLength(): number { return LOOP_MS; }
function step(ms: number): void {
if (fresh) { scatter(); fresh = false; lastT = -1; }
if (lastT >= 0 && lastT < KICK_MS && ms >= KICK_MS) { kick(); }
lastT = ms;
for (let i = 0; i < bubbles.length; i += 1) {
bubbles[i].grow = Math.max(bubbles[i].grow, smooth((ms - START_MS - i * GROW_GAP_MS) / GROW_MS));
}
if (ms >= START_MS) { physicsTick(); }
}
// 동작 줄이기 — 다 부푼 거품으로 SETTLE_TICKS 번 이완을 그리지 않고 한 번에 돌린 뒤 가라앉은 덩어리 한 장면
function finalScene(): void {
scatter();
for (let i = 0; i < bubbles.length; i += 1) { bubbles[i].grow = 1; }
for (let k = 0; k < SETTLE_TICKS; k += 1) { physicsTick(); }
fresh = false;
}
function onWake(): void { }
function hitBubble(b: Bubble): boolean { return hoverX >= 0 && Math.hypot(hoverX - b.x, hoverY - b.y) <= b.r * b.grow; }
function draw(): void {
clearStage();
let hi = -1;
for (let i = bubbles.length - 1; i >= 0; i -= 1) { if (hitBubble(bubbles[i])) { hi = i; break; } }
for (let i = 0; i < bubbles.length; i += 1) {
const b = bubbles[i];
if (b.grow <= 0.01) { continue; }
const k = (i === hi ? 1.06 : 1) * b.grow;
const r = b.r * k;
// 거품 — 왼쪽 위가 밝은 원형 그라디언트(빛이 위에서 온다)
const g = ctx.createRadialGradient(b.x - r * 0.35, b.y - r * 0.4, r * 0.1, b.x, b.y, r);
g.addColorStop(0, rgba(mixRGB(b.color, CREAM, 0.55), 0.96));
g.addColorStop(1, rgba(b.color, 0.92));
ctx.fillStyle = g;
ctx.beginPath();
ctx.arc(b.x, b.y, r, 0, TAU);
ctx.fill();
// 눌린 만큼 테두리 — 겹친 거리가 클수록 진한 분홍 고리
if (b.press > 0.3) {
ctx.lineWidth = 2.5;
ctx.strokeStyle = rgba(PINK, clamp(b.press / 14, 0, 1));
ctx.beginPath();
ctx.arc(b.x, b.y, r + 1.5, 0, TAU);
ctx.stroke();
}
ctx.font = fontOf(b.size * k);
ctx.textAlign = 'center';
ctx.textBaseline = 'alphabetic';
ctx.fillStyle = rgba(BG, 1);
ctx.fillText(b.e.text, b.x, b.y + b.base * k);
}
if (hi >= 0) {
const b = bubbles[hi];
drawTip(b.e.text + ' · ' + countText(b.e.count), b.x, b.y - b.r * b.grow);
}
}
function ranking(): Row[] {
return bubbles.map(function (b: Bubble): Row { return [b.e.text, b.e.count, countText(b.e.count)]; });
}
// 글꼴 준비가 끝나 배치를 계산했는가
let ready = false;
// 정리 뒤(리액트 언마운트)에 늦게 온 글꼴 준비 알림이 일을 시작하지 않게
let alive = true;
// 시연 시계(ms) — 16ms 고정 스텝으로만 늘어난다
let clock = 0;
function wake(): void {
if (!demo) { return; }
demo = false;
root.classList.remove('is-demo');
onWake();
}
// 포인터 자리를 판 좌표(480×300)로 — 화면에 보이는 캔버스 크기와 상관없이
function toBoard(ev: PointerEvent): Pt {
const r = cv.getBoundingClientRect();
return [(ev.clientX - r.left) * W / Math.max(1, r.width), (ev.clientY - r.top) * H / Math.max(1, r.height)];
}
cv.addEventListener('pointermove', function (ev: PointerEvent): void {
const p = toBoard(ev);
hoverX = p[0];
hoverY = p[1];
wake();
if (still && ready) { render(); }
}, { signal: off.signal });
cv.addEventListener('pointerleave', function (): void {
hoverX = -1;
hoverY = -1;
if (still && ready) { render(); }
}, { signal: off.signal });
// 숨긴 목록 — 순위나 횟수가 바뀐 때만 다시 쓴다. 캔버스 요약에는 1~3위를 붙인다
let listKey = '';
function syncList(): void {
const rows = ranking();
const key = rows.map(function (r: Row): string { return r[0] + ':' + r[1]; }).join('|');
if (key === listKey) { return; }
listKey = key;
while (list.firstChild) { list.removeChild(list.firstChild); }
for (let i = 0; i < rows.length; i += 1) {
const li = document.createElement('li');
li.textContent = rows[i][0] + ' — ' + rows[i][2];
list.appendChild(li);
}
const top = rows.slice(0, 3).map(function (r: Row): string { return r[0] + ' ' + r[2]; }).join(', ');
cv.setAttribute('aria-label', baseAria + ' ' + rankHeading + ' ' + top);
}
function render(): void {
draw();
syncList();
}
let rafId = 0;
let lastTs = -1;
let acc = 0;
function frame(ts: number): void {
if (still) { rafId = 0; return; }
if (lastTs < 0) { lastTs = ts; }
// 탭이 숨었다 돌아와도 한 번에 100ms 까지만 따라잡는다
acc += Math.min(ts - lastTs, 100);
lastTs = ts;
let n = 0;
while (acc >= FIXED_DT && n < 6) {
clock += FIXED_DT;
step(clock % loopLength());
acc -= FIXED_DT;
n += 1;
}
render();
rafId = window.requestAnimationFrame(frame);
}
function startLoop(): void {
if (rafId) { return; }
lastTs = -1;
acc = 0;
rafId = window.requestAnimationFrame(frame);
}
function stopLoop(): void {
if (rafId) { window.cancelAnimationFrame(rafId); rafId = 0; }
}
// 동작 줄이기 — 루프를 돌리지 않고 배치를 끝까지 계산한 마지막 한 장면만 그린다
function showStill(): void {
stopLoop();
finalScene();
render();
}
function play(): void {
clock = 0;
step(0);
render();
startLoop();
}
// 설정이 페이지를 연 채 바뀌면 — 켜지면 마지막 장면에서 멈추고, 꺼지면 시연을 처음부터
function onMotionPref(): void {
still = reduceQuery.matches;
if (!ready) { return; }
if (still) { showStill(); } else { play(); }
}
reduceQuery.addEventListener('change', onMotionPref, { signal: off.signal });
window.addEventListener('resize', function (): void {
fitCanvas();
if (ready) { render(); }
}, { signal: off.signal });
function begin(): void {
if (!alive) { return; }
fitCanvas();
build();
ready = true;
if (still) { showStill(); } else { play(); }
}
// 글꼴 — 준비(document.fonts.ready)가 끝난 뒤에 글자 폭을 잰다. 준비 전에 재면 나중에 바뀐 글꼴과 비트 칸이 어긋난다
const fontSet = document.fonts;
// 늦게 도착한 글꼴 — 배치를 마친 뒤 글꼴이 새로 들어오면 글자 폭을 다시 재 배치를 다시 계산한다
fontSet.addEventListener('loadingdone', function (): void {
if (!ready || !alive) { return; }
build();
if (still) { finalScene(); }
render();
}, { signal: off.signal });
fontSet.ready.then(begin);
return function (): void {
alive = false;
stopLoop();
off.abort();
};
}, []);
return (
<div className={cx("wc") + " is-demo"} ref={rootRef}>
<canvas className={cx("wc__canvas")} data-role="canvas" width={480} height={300} role="img" aria-label="단어를 담은 둥근 거품들이 서로 밀어내며 가운데로 모이는 장면."></canvas>
<ol className={cx("wc__list")} data-role="list" aria-label="빈도 순 낱말 목록"></ol>
</div>
);
}06 Word Bubbles That Push Into Place — Measured area 44.077% · moving frames 23/23Original by GODRICH · SCSS and React ship in the zip · Word Cloud JavaScript: 9 Scenes, Spiral to 3D
The post this demo lives in
Word Cloud JavaScript: 9 Scenes, Spiral to 3DWord cloud JavaScript on canvas: if every new vote reshuffles the cloud, nobody can read it. 09 keeps each word in place See all demos in this post
If you like this effect - similar demos
Dashboard UI04 Bubble-Pack Chart Where Circles Push Apart by Value Size9 Data Visualization Chart Types With Real Math
Dashboard UI05 A Pie Chart With Leader-Line Labels That Push Apart When They OverlapPie Chart CSS: 9 Slices That Pop, Tilt and Morph
Dashboard UI03 A Card That Settles Into Its Slot on ReleaseCSS Kanban Board: 9 Demos With Springs and Lerp