04시드 개수 값이 넓히는 보로노이 셀 로더
진행률에 비례해 씨앗점 개수를 늘려 매 프레임 보로노이 다이어그램을 다시 계산하고, 셀이 촘촘해질수록 로더 안쪽이 완성된 모자이크로 채워진다.
쓰임포트폴리오 페이지 로딩·이미지 갤러리 프리로더
MAXSEEDSwobbleRsetTransform

<main class="stage">
<div class="ld" id="ld">
<p class="ld__hint">
<svg class="ld__ico" viewBox="0 0 256 256" aria-hidden="true"><g fill="currentColor"><path d="M232 56v56a8 8 0 0 1-16 0V91.3l-25.6 25.7A80 80 0 1 1 174 60a8 8 0 1 1-9 13.2A64 64 0 1 0 179.7 128H216a8 8 0 0 1 0 16h-56a8 8 0 0 1-8-8V80a8 8 0 0 1 16 0v20.7L192.7 76A80.1 80.1 0 0 0 64 128a8 8 0 0 1-16 0a96 96 0 0 1 163.6-68.3L224 71.3V56a8 8 0 0 1 8 8" opacity=".2"/><path d="M224 48a8 8 0 0 0-8 8v15.3l-11.7-11.6a96 96 0 1 0 27.6 51.6a8 8 0 0 0-15.8 2.5a80 80 0 1 1-23-43l-25.7 25.7A8 8 0 0 0 173 112h56a8 8 0 0 0 8-8V56a8 8 0 0 0-13-8"/></g></svg>
<span>클릭하거나 스페이스바를 누르면 멈추거나 다시 갑니다</span>
</p>
<div class="ld__field" id="field" role="application" aria-label="보로노이 셀 성장 실험판" tabindex="0">
<canvas class="ld__cv" id="cv"></canvas>
<b class="ld__badge" aria-hidden="true"><span class="ld__badgeNum" id="pct">0%</span><span class="ld__badgeUnit">시드</span></b>
</div>
</div>
</main>@use "../../../../site/static/demo-tokens" as *;
// 보로노이 셀 로더 — 씨앗점 개수를 진행률에 비례해 늘리고 매 프레임 최근접-씨앗 격자를 다시 계산한다.
// 움직임은 전부 캔버스 rAF 루프 안에 있다. CSS 는 무대·판·배지만 맡는다(@keyframes 0개 — 077 선례와 같은 이유).
$duration: $dur-loop;
$easing: $ease-pop;
$color: $subject-blue-deep;
@include stage($stage-paper);
.ld {
--paper: #{$subject-cream};
--ink: #{$subject-ink};
--c1: #{$subject-blue};
--c2: #{$subject-mint};
--c3: #{$subject-pink};
--c4: #{$subject-lilac};
--seedpt: #{$subject-ink};
display: flex; flex-direction: column; gap: $sp-2;
width: 100%; max-width: 424px;
}
.ld__hint {
display: flex; align-items: center; gap: $sp-1; margin: 0;
font-weight: 700; font-size: clamp(10px, 2.8vw, 12px); line-height: 1.35;
color: $subject-ink;
}
.ld__ico { width: 16px; height: 16px; flex: 0 0 auto; color: $subject-blue-deep; }
.ld__field {
position: relative; height: 208px;
border-radius: $r-card; overflow: hidden;
background: $subject-cream;
box-shadow: inset 0 0 0 1px rgba($subject-ink, .16);
cursor: pointer;
}
.ld__field:focus-visible { outline: 2px solid $subject-blue-deep; outline-offset: 2px; }
.ld__cv { display: block; width: 100%; height: 100%; }
.ld__badge {
position: absolute; right: $sp-2; top: $sp-2;
display: flex; align-items: baseline; gap: $sp-1;
padding: $sp-1 $sp-2; border-radius: $r-pill;
background: rgba($subject-ink, .78);
color: $subject-cream; font-weight: 700; font-size: 11px;
}
.ld__badgeNum { font-size: 13px; color: $stage-yellow; }
.ld__badgeUnit { font-weight: 700; }
@media (max-width: 340px) {
.ld { gap: $sp-1; }
.ld__field { height: 124px; }
.ld__badge { font-size: 10px; padding: 0 $sp-1; }
.ld__badgeNum { font-size: 11px; }
}
// reduce — 루프를 시작하지 않고 진행률 62% 언저리에서 멈춘 한 장만 그린다.
@media (prefers-reduced-motion: reduce) {
.ld.is-still .ld__field { cursor: default !important; }
.ld.is-still .ld__badge { opacity: .92 !important; }
}html, body {
margin: 0;
overflow: hidden;
}
.stage {
box-sizing: border-box;
min-height: 100vh;
display: grid;
place-items: center;
margin: 0;
background: #ffffff;
font-family: -apple-system, "Segoe UI", "Noto Sans KR", sans-serif;
padding: clamp(8px, 4vw, 24px);
}
.ld {
--paper: #fff7e6;
--ink: #17141a;
--c1: #2f6df6;
--c2: #4cd4a6;
--c3: #ff9ebb;
--c4: #b9a0ff;
--seedpt: #17141a;
display: flex;
flex-direction: column;
gap: 8px;
width: 100%;
max-width: 424px;
}
.ld__hint {
display: flex;
align-items: center;
gap: 4px;
margin: 0;
font-weight: 700;
font-size: clamp(10px, 2.8vw, 12px);
line-height: 1.35;
color: #17141a;
}
.ld__ico {
width: 16px;
height: 16px;
flex: 0 0 auto;
color: #0a4fe8;
}
.ld__field {
position: relative;
height: 208px;
border-radius: 16px;
overflow: hidden;
background: #fff7e6;
box-shadow: inset 0 0 0 1px rgba(23, 20, 26, 0.16);
cursor: pointer;
}
.ld__field:focus-visible {
outline: 2px solid #0a4fe8;
outline-offset: 2px;
}
.ld__cv {
display: block;
width: 100%;
height: 100%;
}
.ld__badge {
position: absolute;
right: 8px;
top: 8px;
display: flex;
align-items: baseline;
gap: 4px;
padding: 4px 8px;
border-radius: 999px;
background: rgba(23, 20, 26, 0.78);
color: #fff7e6;
font-weight: 700;
font-size: 11px;
}
.ld__badgeNum {
font-size: 13px;
color: #ffd23f;
}
.ld__badgeUnit {
font-weight: 700;
}
@media (max-width: 340px) {
.ld {
gap: 4px;
}
.ld__field {
height: 124px;
}
.ld__badge {
font-size: 10px;
padding: 0 4px;
}
.ld__badgeNum {
font-size: 11px;
}
}
@media (prefers-reduced-motion: reduce) {
.ld.is-still .ld__field {
cursor: default !important;
}
.ld.is-still .ld__badge {
opacity: 0.92 !important;
}
}// 보로노이 셀 로더 — 씨앗점 개수를 진행률에 비례해 늘려 매 프레임 보로노이 다이어그램을
// (격자 표본에서 가장 가까운 씨앗 찾기) 다시 계산한다. 셀이 촘촘해질수록 모자이크가 채워진다.
var root = document.getElementById('ld');
var field = document.getElementById('field');
var cv = document.getElementById('cv');
var ctx = cv.getContext('2d');
var pctEl = document.getElementById('pct');
var css = getComputedStyle(root);
var PAPER = css.getPropertyValue('--paper').trim();
var C1 = css.getPropertyValue('--c1').trim();
var C2 = css.getPropertyValue('--c2').trim();
var C3 = css.getPropertyValue('--c3').trim();
var C4 = css.getPropertyValue('--c4').trim();
var SEEDPT = css.getPropertyValue('--seedpt').trim();
var PALETTE = [C1, C2, C3, C4];
function makeRng(seed) {
var s = seed >>> 0;
return function () {
s = (1103515245 * s + 12345) >>> 0;
return (s >>> 8) / 16777216;
};
}
var MAXSEEDS = 16;
var LOOP = 2.0;
var CELL = 9; // 격자 표본 한 칸(px) — 작을수록 더 매끄러운 다이어그램
var rng = makeRng(20260924);
var seeds = [];
for (var i = 0; i < MAXSEEDS; i++) {
seeds.push({
hx: 0.08 + rng() * 0.84, hy: 0.1 + rng() * 0.8, px: 0, py: 0,
wf: 0.7 + rng() * 1.1, wp: rng() * Math.PI * 2 // 개별 흔들림 진동수·위상(LCG 고정) — 씨앗 수가 그대로여도 경계선이 계속 움직인다
});
}
var W = 0, H = 0, dpr = 1, cols = 0, rows = 0, wobbleR = 0;
function fit() {
var r = field.getBoundingClientRect();
dpr = window.devicePixelRatio || 1;
W = r.width; H = r.height;
cv.width = Math.round(W * dpr); cv.height = Math.round(H * dpr);
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
cols = Math.ceil(W / CELL);
rows = Math.ceil(H / CELL);
wobbleR = Math.min(W, H) * 0.035;
for (var i = 0; i < MAXSEEDS; i++) { seeds[i].hx0 = seeds[i].hx * W; seeds[i].hy0 = seeds[i].hy * H; }
}
function draw(sec) {
var t = sec % LOOP;
var p = t / LOOP; // 0→1 진행률 — 활성 씨앗 개수의 목표값
var count = Math.max(2, 2 + Math.floor(p * (MAXSEEDS - 2)));
for (var i = 0; i < MAXSEEDS; i++) {
seeds[i].px = seeds[i].hx0 + Math.sin(sec * seeds[i].wf + seeds[i].wp) * wobbleR;
seeds[i].py = seeds[i].hy0 + Math.cos(sec * seeds[i].wf * 0.86 + seeds[i].wp) * wobbleR;
}
ctx.fillStyle = PAPER;
ctx.fillRect(0, 0, W, H);
for (var r = 0; r < rows; r++) {
var cy = r * CELL + CELL / 2;
for (var c = 0; c < cols; c++) {
var cx = c * CELL + CELL / 2;
var best = 0, bestD = Infinity;
for (var s = 0; s < count; s++) {
var dx = cx - seeds[s].px, dy = cy - seeds[s].py;
var d = dx * dx + dy * dy;
if (d < bestD) { bestD = d; best = s; }
}
ctx.fillStyle = PALETTE[best % PALETTE.length];
ctx.globalAlpha = 0.55;
ctx.fillRect(c * CELL, r * CELL, CELL - 1, CELL - 1);
}
}
ctx.globalAlpha = 1;
for (var k = 0; k < count; k++) {
ctx.fillStyle = SEEDPT;
ctx.beginPath();
ctx.arc(seeds[k].px, seeds[k].py, 3, 0, Math.PI * 2);
ctx.fill();
}
var pct = Math.round((count - 2) / (MAXSEEDS - 2) * 100);
pctEl.textContent = pct + '%';
}
var reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
var paused = false;
var t0 = 0;
var raf = 0;
function togglePause() {
paused = !paused;
root.classList.toggle('is-paused', paused);
}
function restart() {
t0 = performance.now();
draw(0);
}
field.addEventListener('click', function () { togglePause(); });
field.addEventListener('keydown', function (e) {
if (e.key === ' ' || e.key === 'Enter') { e.preventDefault(); togglePause(); }
else if (e.key === 'r' || e.key === 'R') { e.preventDefault(); restart(); }
});
window.addEventListener('resize', function () {
fit();
if (paused || reduce) draw(((performance.now() - t0) / 1000));
});
function frame(now) {
if (!paused) draw((now - t0) / 1000);
raf = requestAnimationFrame(frame);
}
t0 = performance.now();
fit();
if (reduce) {
root.classList.add('is-still');
draw(LOOP * 0.62);
} else {
raf = requestAnimationFrame(frame);
}// VoronoiGrow — vanilla 판(run/395/demo/04-canvas-loader-voronoi-cell-grow-seed-count/index.html) 의 React 포트.
// 씨앗점 개수를 진행률에 비례해 늘리고 매 프레임 최근접-씨앗 격자(보로노이)를 다시 계산한다.
import { useEffect, useRef } from "react";
import type { CSSProperties } from "react";
import styles from "./VoronoiGrow.module.scss";
export type VoronoiGrowProps = {
duration?: string;
easing?: string;
color?: string;
};
type Vars = CSSProperties & { "--duration"?: string; "--easing"?: string; "--color"?: string };
type Box<T> = { current: T };
type KeyEvt = { key: string; preventDefault(): void };
type Seed = { hx: number; hy: number; px: number; py: number; hx0: number; hy0: number; wf: number; wp: number };
function makeRng(seed: number): () => number {
let s = seed >>> 0;
return function () {
s = (1103515245 * s + 12345) >>> 0;
return (s >>> 8) / 16777216;
};
}
const MAXSEEDS = 16;
const LOOP = 2.0;
const CELL = 9;
const FIELD_LABEL = "보로노이 셀 성장 실험판";
function makeSeeds(): Seed[] {
const rng = makeRng(20260924);
const list: Seed[] = [];
for (let i = 0; i < MAXSEEDS; i++) {
list.push({
hx: 0.08 + rng() * 0.84, hy: 0.1 + rng() * 0.8, px: 0, py: 0, hx0: 0, hy0: 0,
wf: 0.7 + rng() * 1.1, wp: rng() * Math.PI * 2, // 개별 흔들림 진동수·위상(LCG 고정) — 씨앗 수가 그대로여도 경계선이 계속 움직인다
});
}
return list;
}
export default function VoronoiGrow({
duration = "2s",
easing = "cubic-bezier(.2, 1.4, .4, 1)", // vanilla $easing: $ease-pop
color = "#0a4fe8", // vanilla $color: $subject-blue-deep
}: VoronoiGrowProps) {
const rootRef = useRef<HTMLDivElement | null>(null);
const fieldRef = useRef<HTMLDivElement | null>(null);
const cvRef = useRef<HTMLCanvasElement | null>(null);
const ctxRef = useRef<CanvasRenderingContext2D | null>(null);
const pctRef = useRef<HTMLSpanElement | null>(null);
const sizeRef = useRef({ w: 0, h: 0, dpr: 1, cols: 0, rows: 0, wobbleR: 0 }) as Box<{ w: number; h: number; dpr: number; cols: number; rows: number; wobbleR: number }>;
const seedsRef = useRef<Seed[]>(makeSeeds()) as Box<Seed[]>;
const pausedRef = useRef(false) as Box<boolean>;
const t0Ref = useRef(0) as Box<number>;
const rafRef = useRef(0) as Box<number>;
const vars: Vars = { "--duration": duration, "--easing": easing, "--color": color };
function reduced(): boolean {
return window.matchMedia("(prefers-reduced-motion: reduce)").matches;
}
function fit(): void {
const field = fieldRef.current;
const cv = cvRef.current;
if (!field || !cv) return;
const r = field.getBoundingClientRect();
const dpr = window.devicePixelRatio || 1;
const size = sizeRef.current;
size.w = r.width; size.h = r.height; size.dpr = dpr;
cv.width = Math.round(r.width * dpr);
cv.height = Math.round(r.height * dpr);
const ctx = ctxRef.current;
if (ctx) ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
size.cols = Math.ceil(r.width / CELL);
size.rows = Math.ceil(r.height / CELL);
size.wobbleR = Math.min(r.width, r.height) * 0.035;
const seeds = seedsRef.current;
for (let i = 0; i < MAXSEEDS; i++) { seeds[i].hx0 = seeds[i].hx * r.width; seeds[i].hy0 = seeds[i].hy * r.height; }
}
function draw(sec: number): void {
const ctx = ctxRef.current;
const root = rootRef.current;
if (!ctx || !root) return;
const size = sizeRef.current;
const W = size.w, H = size.h;
const t = sec % LOOP;
const p = t / LOOP;
const count = Math.max(2, 2 + Math.floor(p * (MAXSEEDS - 2)));
const seeds = seedsRef.current;
const wobbleR = size.wobbleR;
for (let i = 0; i < MAXSEEDS; i++) {
seeds[i].px = seeds[i].hx0 + Math.sin(sec * seeds[i].wf + seeds[i].wp) * wobbleR;
seeds[i].py = seeds[i].hy0 + Math.cos(sec * seeds[i].wf * 0.86 + seeds[i].wp) * wobbleR;
}
const cssv = (n: string) => getComputedStyle(root).getPropertyValue(n).trim();
const PAPER = cssv("--paper"), SEEDPT = cssv("--seedpt");
const PALETTE = [cssv("--c1"), cssv("--c2"), cssv("--c3"), cssv("--c4")];
ctx.fillStyle = PAPER;
ctx.fillRect(0, 0, W, H);
for (let r = 0; r < size.rows; r++) {
const cy = r * CELL + CELL / 2;
for (let c = 0; c < size.cols; c++) {
const cx = c * CELL + CELL / 2;
let best = 0, bestD = Infinity;
for (let s = 0; s < count; s++) {
const dx = cx - seeds[s].px, dy = cy - seeds[s].py;
const d = dx * dx + dy * dy;
if (d < bestD) { bestD = d; best = s; }
}
ctx.fillStyle = PALETTE[best % PALETTE.length];
ctx.globalAlpha = 0.55;
ctx.fillRect(c * CELL, r * CELL, CELL - 1, CELL - 1);
}
}
ctx.globalAlpha = 1;
for (let k = 0; k < count; k++) {
ctx.fillStyle = SEEDPT;
ctx.beginPath();
ctx.arc(seeds[k].px, seeds[k].py, 3, 0, Math.PI * 2);
ctx.fill();
}
const pct = Math.round((count - 2) / (MAXSEEDS - 2) * 100);
if (pctRef.current) pctRef.current.textContent = pct + "%";
}
function togglePause(): void {
pausedRef.current = !pausedRef.current;
const root = rootRef.current;
if (root) root.classList.toggle("is-paused", pausedRef.current);
}
function restart(): void {
t0Ref.current = performance.now();
draw(0);
}
function onKey(e: KeyEvt): void {
if (e.key === " " || e.key === "Enter") { e.preventDefault(); togglePause(); }
else if (e.key === "r" || e.key === "R") { e.preventDefault(); restart(); }
}
function onClick(): void {
togglePause();
}
function onResize(): void {
fit();
if (pausedRef.current || reduced()) draw((performance.now() - t0Ref.current) / 1000);
}
function frame(now: number): void {
if (!pausedRef.current) draw((now - t0Ref.current) / 1000);
rafRef.current = requestAnimationFrame(frame);
}
useEffect(() => {
const cv = cvRef.current;
if (!cv) return;
ctxRef.current = cv.getContext("2d");
if (!ctxRef.current) return;
t0Ref.current = performance.now();
fit();
window.addEventListener("resize", onResize);
if (reduced()) {
const root = rootRef.current;
if (root) root.classList.add("is-still");
draw(LOOP * 0.62);
} else {
rafRef.current = requestAnimationFrame(frame);
}
return () => {
window.removeEventListener("resize", onResize);
cancelAnimationFrame(rafRef.current);
};
}, []);
return (
<main className={styles.stage}>
<div className={styles.root} ref={rootRef} style={vars}>
<p className={styles.hint}>
<svg className={styles.ico} viewBox="0 0 256 256" aria-hidden="true"><g fill="currentColor"><path d="M232 56v56a8 8 0 0 1-16 0V91.3l-25.6 25.7A80 80 0 1 1 174 60a8 8 0 1 1-9 13.2A64 64 0 1 0 179.7 128H216a8 8 0 0 1 0 16h-56a8 8 0 0 1-8-8V80a8 8 0 0 1 16 0v20.7L192.7 76A80.1 80.1 0 0 0 64 128a8 8 0 0 1-16 0a96 96 0 0 1 163.6-68.3L224 71.3V56a8 8 0 0 1 8 8" opacity=".2"/><path d="M224 48a8 8 0 0 0-8 8v15.3l-11.7-11.6a96 96 0 1 0 27.6 51.6a8 8 0 0 0-15.8 2.5a80 80 0 1 1-23-43l-25.7 25.7A8 8 0 0 0 173 112h56a8 8 0 0 0 8-8V56a8 8 0 0 0-13-8"/></g></svg>
<span>클릭하거나 스페이스바를 누르면 멈추거나 다시 갑니다</span>
</p>
<div
className={styles.field}
ref={fieldRef}
role="application"
aria-label={FIELD_LABEL}
tabIndex={0}
onClick={onClick}
onKeyDown={onKey}
>
<canvas className={styles.cv} ref={cvRef}></canvas>
<b className={styles.badge} aria-hidden="true"><span className={styles.badgeNum} ref={pctRef}>0%</span><span className={styles.badgeUnit}>시드</span></b>
</div>
</div>
</main>
);
}04 시드 개수 값이 넓히는 보로노이 셀 로더 — 측정 누적면적 37.312% · 움직인 프레임 23/23GODRICH 원작 · zip 에 SCSS·React 포함 · 캔버스 로딩 애니메이션 효과 9가지 — 코드 그대로
이 데모가 속한 글
캔버스 로딩 애니메이션 효과 9가지 — 코드 그대로로딩 애니메이션 효과 를 캔버스로 만들 때 값 하나만 정해두면 나머지는 계산이 다 합니다. 감쇠 상수 0.92 가 중력 로더의 튕김 높이를 줄이고, 셀룰러 오토마타는 생존 규칙 값 하나로 세대마다 채워진 셀 비율을 이 글의 데모 전부 보기

