06A Jellyfish That Lurches Forward Each Time Its Bell Squeezes
Each cycle of a quick squeeze and a slow release pushes the bell forward once before water drag slows it, while the tentacles below trail behind on inertia and sway.
Best forIntro screen for a meditation or sleep app
PULSE_IMPULSEWATER_DRAGLINK_PASSES

<main class="stage">
<div class="cf is-demo" id="cf">
<canvas class="cf__canvas" data-role="canvas" width="480" height="300" role="img" aria-label="Two jellyfish that lurch forward each time their bells squeeze, tentacles swaying behind."></canvas>
<button class="cf__pause" data-role="pause" type="button" aria-pressed="false">Pause</button>
</div>
</main>@use "../../../../site/static/demo-tokens" as *;
@include stage($stage-paper);
.cf {
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-cream;
}
.cf__canvas {
position: absolute;
inset: 0;
display: block;
width: 100%;
height: 100%;
}
.cf__pause {
position: absolute;
right: $sp-3;
bottom: $sp-3;
padding: $sp-1 $sp-3;
border: 2px solid $subject-ink;
border-radius: $r-pill;
background: $subject-ink;
color: $subject-cream;
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;
}
// 눌린 상태(멈춤) — 바탕과 글자색을 뒤집어 aria-pressed 가 눈에도 보이게
.cf__pause[aria-pressed="true"] {
background: $subject-cream;
color: $subject-ink;
}
.cf__pause:hover {
transform: translateY(-2px);
}
.cf__pause:active {
transform: translateY(1px);
}
.cf__pause:focus-visible {
outline: 3px solid $subject-ink;
outline-offset: 3px;
}
// 상태 줄 — 지금 어떤 행동 중인지 글자로. 시연 중에는 aria-live off, 사람이 처음 손대면 polite
.cf__status {
position: absolute;
left: $sp-3;
top: $sp-3;
margin: 0;
padding: $sp-1 $sp-3;
border-radius: $r-pill;
background: $subject-ink;
color: $subject-cream;
font-weight: 700;
font-size: 12px;
line-height: 1.6;
pointer-events: none;
}
@media (max-width: 340px) {
.cf__pause,
.cf__status { font-size: 11px; padding: $sp-1 $sp-2; }
}
// 동작 줄이기 — 장면은 스크립트가 쉬는 자세 한 장으로 멈춘다. 버튼도 떠오르지 않게
@media (prefers-reduced-motion: reduce) {
.cf__pause { transition: none !important; }
.cf__pause:hover,
.cf__pause: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: #ffffff;
font-family: -apple-system, "Segoe UI", "Noto Sans KR", sans-serif;
padding: clamp(8px, 4vw, 24px);
}
.cf {
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: #fff7e6;
}
.cf__canvas {
position: absolute;
inset: 0;
display: block;
width: 100%;
height: 100%;
}
.cf__pause {
position: absolute;
right: 12px;
bottom: 12px;
padding: 4px 12px;
border: 2px solid #17141a;
border-radius: 999px;
background: #17141a;
color: #fff7e6;
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);
}
.cf__pause[aria-pressed=true] {
background: #fff7e6;
color: #17141a;
}
.cf__pause:hover {
transform: translateY(-2px);
}
.cf__pause:active {
transform: translateY(1px);
}
.cf__pause:focus-visible {
outline: 3px solid #17141a;
outline-offset: 3px;
}
.cf__status {
position: absolute;
left: 12px;
top: 12px;
margin: 0;
padding: 4px 12px;
border-radius: 999px;
background: #17141a;
color: #fff7e6;
font-weight: 700;
font-size: 12px;
line-height: 1.6;
pointer-events: none;
}
@media (max-width: 340px) {
.cf__pause,
.cf__status {
font-size: 11px;
padding: 4px 8px;
}
}
@media (prefers-reduced-motion: reduce) {
.cf__pause {
transition: none !important;
}
.cf__pause:hover,
.cf__pause:active {
transform: none !important;
}
}(function () {
const root = document.getElementById("cf");
if (!root) return;
// 판 좌표 — 캔버스 안은 늘 480×300. 화면에 보이는 크기와 상관없이 계산은 이 좌표로 한다
const W = 480;
const H = 300;
const TAU = Math.PI * 2;
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 wrapAngle(a) {
let r = a;
while (r > Math.PI) {
r -= TAU;
}
while (r < -Math.PI) {
r += TAU;
}
return r;
}
// 따라가기 비율 — 1 − e^(−rate·dt). 프레임 시간이 달라도 1초에 같은 만큼 다가간다
function follow(rate, dt) { return 1 - Math.exp(-rate * dt); }
// 시드 고정 난수 — 같은 시드면 같은 흔들림·배치가 다시 나온다 (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차원 값 노이즈 — 정수 자리마다 시드로 정한 값(-1~1)을 두고 사이는 부드러운 보간. 흔들림·배회 방향에 쓴다
const NOISE_TABLE = new Float32Array(256);
const noiseRng = makeRng(480);
for (let i = 0; i < 256; i += 1) {
NOISE_TABLE[i] = noiseRng() * 2 - 1;
}
function smoothNoise(x) {
const i = Math.floor(x);
const f = x - i;
const u = f * f * (3 - 2 * f);
return lerp(NOISE_TABLE[i & 255], NOISE_TABLE[(i + 1) & 255], u);
}
// 8자 길 — 가로로 한 번(sin θ), 세로로 두 번(sin 2θ) 흔들리는 점. 판 가운데를 지나는 두 고리를 period 초에 한 바퀴
function figureEight(t, ax, ay, period) {
const a = TAU * t / period;
return [W / 2 + ax * Math.sin(a), H / 2 + ay * Math.sin(2 * a)];
}
// 파스텔 팔레트 — 크림·옅은 민트 바탕 위에 파스텔 생물, 윤곽선과 그림자는 진한 잉크색으로 명도 차를 둔다
const PAPER = [251, 247, 238];
const PAPER_LOW = [222, 242, 234];
const INK = [58, 50, 74];
const CREAM = [255, 251, 242];
const CORAL = [244, 162, 144];
const LAVENDER = [188, 170, 236];
const BUTTER = [246, 222, 140];
const SAGE = [156, 204, 164];
const PINK = [244, 176, 200];
const SKY = [156, 204, 236];
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 shade(c, k) { return [c[0] * k, c[1] * k, c[2] * k]; }
const canvasEl = root.querySelector('[data-role="canvas"]');
const pauseEl = root.querySelector('[data-role="pause"]');
const ctxRaw = canvasEl ? canvasEl.getContext('2d') : null;
if (!canvasEl || !ctxRaw || !pauseEl) {
return;
}
const cv = canvasEl;
const ctx = ctxRaw;
const pauseBtn = pauseEl;
// 목표점(판 좌표)과 그 속도(px/초) — 8자 길 또는 포인터. 그리기에서 눈동자 방향·목표 표시에 쓴다
let tx = W / 2;
let ty = H / 2;
let tvx = 0;
let tvy = 0;
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(top, bottom) {
const g = ctx.createLinearGradient(0, 0, 0, H);
g.addColorStop(0, rgba(top, 1));
g.addColorStop(1, rgba(bottom, 1));
ctx.fillStyle = g;
ctx.fillRect(0, 0, W, H);
}
// 점들을 지나는 매끈한 닫힌 곡선 — 이웃 두 점의 가운데를 잇고 점 자체는 2차 곡선의 조절점으로 쓴다
function smoothClosed(pts) {
const n = pts.length / 2;
ctx.beginPath();
ctx.moveTo((pts[2 * (n - 1)] + pts[0]) / 2, (pts[2 * (n - 1) + 1] + pts[1]) / 2);
for (let i = 0; i < n; i += 1) {
const j = (i + 1) % n;
ctx.quadraticCurveTo(pts[2 * i], pts[2 * i + 1], (pts[2 * i] + pts[2 * j]) / 2, (pts[2 * i + 1] + pts[2 * j + 1]) / 2);
}
ctx.closePath();
}
function fillShape(pts, fill, line) {
smoothClosed(pts);
ctx.fillStyle = rgba(fill, 1);
ctx.fill();
if (line > 0) {
ctx.lineWidth = line;
ctx.lineJoin = 'round';
ctx.strokeStyle = rgba(INK, 1);
ctx.stroke();
}
}
// 바닥 그림자 — 같은 윤곽을 (ox, oy) 만큼 밀어 옅은 잉크색으로
function dropShadow(pts, ox, oy, alpha) {
ctx.save();
ctx.translate(ox, oy);
smoothClosed(pts);
ctx.fillStyle = rgba(INK, alpha);
ctx.fill();
ctx.restore();
}
// 눈 — 흰자 위 눈동자를 (lookX, lookY) 쪽으로 반지름의 0.4 만큼 민다. open 0~1 은 위 눈꺼풀이 덮는 정도의 반대
function drawEye(x, y, r, lookX, lookY, open) {
const a = Math.atan2(lookY - y, lookX - x);
ctx.beginPath();
ctx.arc(x, y, r, 0, TAU);
ctx.fillStyle = rgba(CREAM, 1);
ctx.fill();
ctx.lineWidth = 1.5;
ctx.strokeStyle = rgba(INK, 1);
ctx.stroke();
ctx.beginPath();
ctx.arc(x + Math.cos(a) * r * 0.4, y + Math.sin(a) * r * 0.4, r * 0.55, 0, TAU);
ctx.fillStyle = rgba(INK, 1);
ctx.fill();
if (open < 1) {
ctx.save();
ctx.beginPath();
ctx.arc(x, y, r + 0.5, 0, TAU);
ctx.clip();
ctx.fillStyle = rgba(INK, 0.85);
ctx.fillRect(x - r - 1, y - r - 1, 2 * r + 2, (2 * r + 2) * (1 - open));
ctx.restore();
}
}
// 목표 표시 — 잉크색 고리와 점. 생물이 무엇을 쫓는지 보이게
function drawTarget(x, y) {
// 동작 줄이기의 쉬는 자세에서는 포인터가 올라왔을 때만 보인다
if (still && !ptrOn) {
return;
}
ctx.beginPath();
ctx.arc(x, y, 7, 0, TAU);
ctx.lineWidth = 2;
ctx.strokeStyle = rgba(INK, 0.55);
ctx.stroke();
ctx.beginPath();
ctx.arc(x, y, 2.5, 0, TAU);
ctx.fillStyle = rgba(INK, 0.7);
ctx.fill();
}
// 06 해파리 — 갓이 PULSE_PERIOD 초마다 빠르게 오므리고(주기의 SQUEEZE_SHARE) 천천히 편다.
// 오므리는 만큼(수축량의 증가분) 갓이 향한 쪽으로 PULSE_IMPULSE(px/초)를 받고, 물의 저항 WATER_DRAG(1/초)로 속도가 줄어든다
const PULSE_PERIOD = 1.2;
const SQUEEZE_SHARE = 0.3;
const PULSE_IMPULSE = 160;
const WATER_DRAG = 1.6;
// 갓이 1초에 도는 각(라디안) — 목표 쪽으로 천천히 고개를 튼다
const JELLY_TURN = 2.4;
// 갓이 가장 오므렸을 때 폭이 줄어드는 비율
const SQUEEZE_DEPTH = 0.3;
const JELLY_MARGIN = 55;
// 촉수 — 갓 가장자리에 TENTACLE_COUNT 개, 마디 TENTACLE_LINKS 개, 간격 LINK_GAP(px).
// 마디마다 직전 위치와의 차이(관성)에 TRAIL_KEEP 을 곱해 이어 가고 아래로 SINK(px/초²) 만큼 가라앉은 뒤, 간격 맞추기를 LINK_PASSES 번 되풀이한다
const TENTACLE_COUNT = 5;
const TENTACLE_LINKS = 10;
const LINK_GAP = 11;
const TRAIL_KEEP = 0.92;
const SINK = 30;
const LINK_PASSES = 3;
const PREWARM = 3;
function pathAt(t) { return figureEight(t, 170, 85, 10); }
function makeJelly(size, lag, phase) {
const j = { x: 0, y: 0, vx: 0, vy: 0, heading: -Math.PI / 2, phase: phase, squeeze: 0, size: size, lag: lag, xs: [], ys: [], pxs: [], pys: [] };
for (let k = 0; k < TENTACLE_COUNT; k += 1) {
j.xs.push(new Float64Array(TENTACLE_LINKS));
j.ys.push(new Float64Array(TENTACLE_LINKS));
j.pxs.push(new Float64Array(TENTACLE_LINKS));
j.pys.push(new Float64Array(TENTACLE_LINKS));
}
return j;
}
const jellies = [makeJelly(40, 0, 0), makeJelly(27, 3.4, 0.45)];
let jellyClock = 0;
// 수축량 0~1 — 주기 앞 SQUEEZE_SHARE 동안 빠르게 0→1, 나머지 동안 천천히 1→0
function squeezeAt(phase) {
const u = phase - Math.floor(phase);
return u < SQUEEZE_SHARE ? smooth(u / SQUEEZE_SHARE) : 1 - smooth((u - SQUEEZE_SHARE) / (1 - SQUEEZE_SHARE));
}
// 촉수 뿌리 — 갓 뒤쪽 가장자리를 따라 고르게. 갓이 오므리면 폭과 함께 좁아진다
function rimOf(j, k) {
const back = j.heading + Math.PI;
const across = (k / (TENTACLE_COUNT - 1) - 0.5) * 1.6 * j.size * (1 - SQUEEZE_DEPTH * j.squeeze);
return [j.x + Math.cos(back) * j.size * 0.25 + Math.cos(j.heading + Math.PI / 2) * across, j.y + Math.sin(back) * j.size * 0.25 + Math.sin(j.heading + Math.PI / 2) * across];
}
function hangTentacles(j) {
for (let k = 0; k < TENTACLE_COUNT; k += 1) {
const r = rimOf(j, k);
for (let i = 0; i < TENTACLE_LINKS; i += 1) {
j.xs[k][i] = r[0];
j.ys[k][i] = r[1] + i * LINK_GAP;
j.pxs[k][i] = j.xs[k][i];
j.pys[k][i] = j.ys[k][i];
}
}
}
// 촉수 한 걸음 — 관성(직전 위치와의 차 × TRAIL_KEEP) + 가라앉기(SINK × dt²), 뿌리는 갓에 고정, 간격 맞추기 LINK_PASSES 번
function stepTentacle(xs, ys, pxs, pys, rx, ry, dt, passes) {
for (let i = 1; i < TENTACLE_LINKS; i += 1) {
const nx = xs[i] + (xs[i] - pxs[i]) * TRAIL_KEEP;
const ny = ys[i] + (ys[i] - pys[i]) * TRAIL_KEEP + SINK * dt * dt;
pxs[i] = xs[i];
pys[i] = ys[i];
xs[i] = nx;
ys[i] = ny;
}
xs[0] = rx;
ys[0] = ry;
pxs[0] = rx;
pys[0] = ry;
for (let p = 0; p < passes; p += 1) {
for (let i = 1; i < TENTACLE_LINKS; i += 1) {
const dx = xs[i] - xs[i - 1];
const dy = ys[i] - ys[i - 1];
const d = Math.hypot(dx, dy) || 1;
const diff = (d - LINK_GAP) / d;
// 뿌리 쪽 첫 마디는 뿌리가 고정이라 혼자 다 움직이고, 나머지는 둘이 반씩
if (i === 1) {
xs[i] -= dx * diff;
ys[i] -= dy * diff;
}
else {
xs[i - 1] += dx * diff * 0.5;
ys[i - 1] += dy * diff * 0.5;
xs[i] -= dx * diff * 0.5;
ys[i] -= dy * diff * 0.5;
}
}
}
}
function stepJelly(j, dt, gx, gy) {
const want = Math.atan2(gy - j.y, gx - j.x);
j.heading = wrapAngle(j.heading + clamp(wrapAngle(want - j.heading), -JELLY_TURN * dt, JELLY_TURN * dt));
j.phase += dt / PULSE_PERIOD;
const before = j.squeeze;
j.squeeze = squeezeAt(j.phase);
const push = Math.max(0, j.squeeze - before) * PULSE_IMPULSE;
j.vx += Math.cos(j.heading) * push;
j.vy += Math.sin(j.heading) * push;
const drag = Math.exp(-WATER_DRAG * dt);
j.vx *= drag;
j.vy *= drag;
j.x += j.vx * dt;
j.y += j.vy * dt;
// 판 가장자리 — JELLY_MARGIN(px) 안으로 들어오면 넘친 거리 × 4 만큼 안쪽으로 속도를 돌려 판 밖으로 나가지 않게
const ox = j.x < JELLY_MARGIN ? JELLY_MARGIN - j.x : (j.x > W - JELLY_MARGIN ? W - JELLY_MARGIN - j.x : 0);
const oy = j.y < JELLY_MARGIN ? JELLY_MARGIN - j.y : (j.y > H - JELLY_MARGIN ? H - JELLY_MARGIN - j.y : 0);
j.vx += ox * 4 * dt;
j.vy += oy * 4 * dt;
for (let k = 0; k < TENTACLE_COUNT; k += 1) {
const r = rimOf(j, k);
stepTentacle(j.xs[k], j.ys[k], j.pxs[k], j.pys[k], r[0], r[1], dt, LINK_PASSES);
}
}
function reset() {
jellyClock = 0;
for (let n = 0; n < jellies.length; n += 1) {
const j = jellies[n];
const p = pathAt(-j.lag);
j.x = p[0];
j.y = p[1] + 30;
j.vx = 0;
j.vy = 0;
j.heading = -Math.PI / 2;
j.phase = n * 0.45;
j.squeeze = squeezeAt(j.phase);
hangTentacles(j);
}
}
// 큰 해파리는 목표를, 작은 해파리는 같은 8자 길을 lag 초 늦게 쫓는다
function update(dt, tx, ty, tvx, tvy) {
jellyClock += dt;
for (let n = 0; n < jellies.length; n += 1) {
const j = jellies[n];
if (j.lag === 0) {
stepJelly(j, dt, tx, ty);
}
else {
const p = pathAt(jellyClock - j.lag);
stepJelly(j, dt, p[0], p[1]);
}
}
}
// 쉬는 자세 — 두 마리 모두 위를 보고 촉수를 곧게 늘어뜨린 채 반쯤 편 갓
function restPose() {
const spots = [W / 2 - 60, H / 2 - 40, W / 2 + 110, H / 2 - 10];
for (let n = 0; n < jellies.length; n += 1) {
const j = jellies[n];
j.x = spots[n * 2];
j.y = spots[n * 2 + 1];
j.heading = -Math.PI / 2;
j.squeeze = 0.3;
hangTentacles(j);
}
}
// 물빛 바탕 — 위는 옅은 라벤더, 아래는 옅은 하늘색
const SEA_TOP = [238, 234, 250];
const SEA_LOW = [218, 236, 246];
function drawJelly(j, bell, frill) {
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
// 촉수 물결 — 박동 위상을 따라 갓 옆 방향으로 흔든다. 끝으로 갈수록(i 가 클수록) 크게
const nx = Math.cos(j.heading + Math.PI / 2);
const ny = Math.sin(j.heading + Math.PI / 2);
for (let k = 0; k < TENTACLE_COUNT; k += 1) {
for (let pass = 0; pass < 2; pass += 1) {
ctx.beginPath();
ctx.moveTo(j.xs[k][0], j.ys[k][0]);
for (let i = 1; i < TENTACLE_LINKS; i += 1) {
const wob = Math.sin(j.phase * TAU - i * 0.8 + k * 1.3) * i * 0.7 * j.size / 40;
ctx.lineTo(j.xs[k][i] + nx * wob, j.ys[k][i] + ny * wob);
}
ctx.lineWidth = (pass === 0 ? 5 : 2.6) * j.size / 40;
ctx.strokeStyle = pass === 0 ? rgba(INK, 0.9) : rgba(frill, 1);
ctx.stroke();
}
}
// 갓 — 진행 방향이 위가 되게 돌린 좌표에서 반타원 지붕 + 물결 가장자리. 오므릴수록 좁고 길어진다
const w = j.size * (1 - SQUEEZE_DEPTH * j.squeeze);
const h = j.size * 0.85 * (1 + 0.35 * j.squeeze);
const base = j.size * 0.25;
ctx.save();
ctx.translate(j.x, j.y);
ctx.rotate(j.heading + Math.PI / 2);
ctx.beginPath();
ctx.ellipse(0, base, w, h, 0, Math.PI, TAU);
const lumps = 6;
for (let s = 0; s < lumps; s += 1) {
const x0 = w - 2 * w * s / lumps;
const x1 = w - 2 * w * (s + 1) / lumps;
ctx.quadraticCurveTo((x0 + x1) / 2, base + j.size * 0.16, x1, base);
}
ctx.closePath();
ctx.fillStyle = rgba(bell, 0.94);
ctx.fill();
ctx.lineWidth = 2.4;
ctx.strokeStyle = rgba(INK, 1);
ctx.stroke();
// 속 무늬 — 갓 안쪽 네 잎. 갓 크기를 따라 줄고 는다
ctx.fillStyle = rgba(frill, 0.9);
for (let p = 0; p < 4; p += 1) {
const px = (p - 1.5) * w * 0.34;
ctx.beginPath();
ctx.ellipse(px, base - h * 0.42, w * 0.13, h * 0.24, (p - 1.5) * 0.25, 0, TAU);
ctx.fill();
}
// 하이라이트 — 지붕 왼쪽 위에 크림색 호
ctx.beginPath();
ctx.ellipse(-w * 0.35, base - h * 0.62, w * 0.22, h * 0.12, -0.5, 0, TAU);
ctx.fillStyle = rgba(CREAM, 0.85);
ctx.fill();
ctx.restore();
}
function draw() {
clearStage(SEA_TOP, SEA_LOW);
drawJelly(jellies[1], PINK, LAVENDER);
drawJelly(jellies[0], LAVENDER, PINK);
for (let s = -1; s <= 1; s += 2) {
const j = jellies[0];
const ex = j.x + Math.cos(j.heading + Math.PI / 2) * s * 10 - Math.cos(j.heading) * 2;
const ey = j.y + Math.sin(j.heading + Math.PI / 2) * s * 10 - Math.sin(j.heading) * 2;
drawEye(ex, ey, 4.5, tx, ty, 1);
}
drawTarget(tx, ty);
}
// 한 프레임에 넘기는 시간 상한(초) — 탭을 오래 숨겼다 돌아온 첫 프레임에도 50ms 까지만 계산에 넣는다
const DT_MAX = 0.05;
// 미리 돌리기 — 첫 장면을 그리기 전에 PREWARM 초를 1/60초 걸음으로 계산해 생물이 길 위에 자리 잡은 채 시작한다
const PREWARM_STEP = 1 / 60;
// 시연 시계(초) — 8자 길 위의 자리를 정한다
let simTime = 0;
// 포인터(판 좌표) — 판 위에 있으면 목표를 포인터 쪽으로 옮긴다. 떠나면 다시 8자 길로 서서히 돌아간다
let ptrX = W / 2;
let ptrY = H / 2;
let ptrOn = false;
let ptrBlend = 0;
let paused = false;
const reduceQuery = window.matchMedia('(prefers-reduced-motion: reduce)');
// 페이지를 연 채 동작 줄이기 설정을 바꿔도 change 리스너가 이 값을 다시 읽는다
let still = reduceQuery.matches;
// 자동 시연 중인가 — 사람이 처음 손대면 시연 표시를 떼고 알림 줄을 polite 로 켠다
let demo = root.classList.contains('is-demo');
// 리스너는 한 묶음으로 달고 정리할 때 한 번에 뗀다
const off = new AbortController();
function wake() {
if (!demo) {
return;
}
demo = false;
root.classList.remove('is-demo');
const live = root.querySelector('[aria-live]');
if (live) {
live.setAttribute('aria-live', 'polite');
}
}
// 목표 옮기기 — 8자 길 자리와 포인터 자리를 ptrBlend 비율로 섞고, 그 변화로 목표 속도를 잰다
function moveTarget(dt) {
const p = pathAt(simTime);
ptrBlend = lerp(ptrBlend, ptrOn ? 1 : 0, follow(4, dt));
const nx = lerp(p[0], ptrX, ptrBlend);
const ny = lerp(p[1], ptrY, ptrBlend);
if (dt > 0) {
tvx = lerp(tvx, (nx - tx) / dt, follow(12, dt));
tvy = lerp(tvy, (ny - ty) / dt, follow(12, dt));
}
tx = nx;
ty = ny;
}
function advance(dt) {
simTime += dt;
moveTarget(dt);
update(dt, tx, ty, tvx, tvy);
}
let rafId = 0;
let lastTs = -1;
function frame(ts) {
if (still || paused) {
rafId = 0;
return;
}
if (lastTs < 0) {
lastTs = ts;
}
const dt = Math.min((ts - lastTs) / 1000, DT_MAX);
lastTs = ts;
if (dt > 0) {
advance(dt);
}
draw();
rafId = window.requestAnimationFrame(frame);
}
function startLoop() {
if (rafId) {
return;
}
// 시계 다시 맞추기 — 멈췄던 사이의 시간을 첫 프레임 dt 로 넘기지 않는다
lastTs = -1;
rafId = window.requestAnimationFrame(frame);
}
function stopLoop() {
if (rafId) {
window.cancelAnimationFrame(rafId);
rafId = 0;
}
}
// 동작 줄이기 — 루프를 돌리지 않고 쉬는 자세 한 장면만 그린다
function showRest() {
stopLoop();
reset();
restPose();
draw();
}
function play() {
reset();
simTime = 0;
const p = pathAt(0);
tx = p[0];
ty = p[1];
tvx = 0;
tvy = 0;
for (let t = 0; t < PREWARM; t += PREWARM_STEP) {
advance(PREWARM_STEP);
}
draw();
if (!paused) {
startLoop();
}
}
function setPointer(ev) {
const r = cv.getBoundingClientRect();
ptrX = (ev.clientX - r.left) * W / Math.max(1, r.width);
ptrY = (ev.clientY - r.top) * H / Math.max(1, r.height);
ptrOn = true;
wake();
// 동작 줄이기에서도 입력은 화면에 남는다 — 쉬는 자세 그대로 눈과 목표 표시만 포인터 쪽으로 다시 그린다
if (still) {
tx = ptrX;
ty = ptrY;
draw();
}
}
cv.addEventListener('pointermove', setPointer, { signal: off.signal });
cv.addEventListener('pointerdown', setPointer, { signal: off.signal });
function leavePointer() { ptrOn = false; }
cv.addEventListener('pointerleave', leavePointer, { signal: off.signal });
cv.addEventListener('pointercancel', leavePointer, { signal: off.signal });
pauseBtn.addEventListener('click', function () {
paused = !paused;
pauseBtn.setAttribute('aria-pressed', paused ? 'true' : 'false');
wake();
if (paused) {
stopLoop();
}
else if (!still) {
startLoop();
}
}, { signal: off.signal });
// 탭이 숨으면 루프를 멈추고, 돌아오면 시계를 다시 맞춰 시작한다 — 숨은 동안의 몇 초가 한 프레임에 몰리지 않게
document.addEventListener('visibilitychange', function () {
if (document.hidden) {
stopLoop();
}
else if (!paused && !still) {
startLoop();
}
}, { signal: off.signal });
// 설정이 페이지를 연 채 바뀌면 — 켜지면 쉬는 자세로 멈추고, 꺼지면 시연을 처음부터
reduceQuery.addEventListener('change', function () {
still = reduceQuery.matches;
if (still) {
showRest();
}
else {
play();
}
}, { signal: off.signal });
window.addEventListener('resize', function () {
fitCanvas();
draw();
}, { signal: off.signal });
fitCanvas();
if (still) {
showRest();
}
else {
play();
}
return function () {
stopLoop();
off.abort();
};
})();// JellyfishPulseDrift - vanilla 판(06-creature-jellyfish-pulse-drift) 의 React 포트. 같은 계산을 useEffect 안에서 돌린다.
import { useEffect, useRef } from "react";
import styles from "./JellyfishPulseDrift.module.scss";
const cx = (s: string): string => s.split(" ").map((n) => styles[n] ?? n).join(" ");
export default function JellyfishPulseDrift() {
const rootRef = useRef<HTMLDivElement | null>(null);
useEffect(() => {
const rootEl = rootRef.current;
if (!rootEl) return;
const root: HTMLElement = rootEl;
type Pt = [number, number];
type RGB = [number, number, number];
// 판 좌표 — 캔버스 안은 늘 480×300. 화면에 보이는 크기와 상관없이 계산은 이 좌표로 한다
const W = 480;
const H = 300;
const TAU = Math.PI * 2;
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 wrapAngle(a: number): number {
let r = a;
while (r > Math.PI) { r -= TAU; }
while (r < -Math.PI) { r += TAU; }
return r;
}
// 따라가기 비율 — 1 − e^(−rate·dt). 프레임 시간이 달라도 1초에 같은 만큼 다가간다
function follow(rate: number, dt: number): number { return 1 - Math.exp(-rate * dt); }
// 시드 고정 난수 — 같은 시드면 같은 흔들림·배치가 다시 나온다 (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차원 값 노이즈 — 정수 자리마다 시드로 정한 값(-1~1)을 두고 사이는 부드러운 보간. 흔들림·배회 방향에 쓴다
const NOISE_TABLE = new Float32Array(256);
const noiseRng = makeRng(480);
for (let i = 0; i < 256; i += 1) { NOISE_TABLE[i] = noiseRng() * 2 - 1; }
function smoothNoise(x: number): number {
const i = Math.floor(x);
const f = x - i;
const u = f * f * (3 - 2 * f);
return lerp(NOISE_TABLE[i & 255], NOISE_TABLE[(i + 1) & 255], u);
}
// 8자 길 — 가로로 한 번(sin θ), 세로로 두 번(sin 2θ) 흔들리는 점. 판 가운데를 지나는 두 고리를 period 초에 한 바퀴
function figureEight(t: number, ax: number, ay: number, period: number): Pt {
const a = TAU * t / period;
return [W / 2 + ax * Math.sin(a), H / 2 + ay * Math.sin(2 * a)];
}
// 파스텔 팔레트 — 크림·옅은 민트 바탕 위에 파스텔 생물, 윤곽선과 그림자는 진한 잉크색으로 명도 차를 둔다
const PAPER: RGB = [251, 247, 238];
const PAPER_LOW: RGB = [222, 242, 234];
const INK: RGB = [58, 50, 74];
const CREAM: RGB = [255, 251, 242];
const CORAL: RGB = [244, 162, 144];
const LAVENDER: RGB = [188, 170, 236];
const BUTTER: RGB = [246, 222, 140];
const SAGE: RGB = [156, 204, 164];
const PINK: RGB = [244, 176, 200];
const SKY: RGB = [156, 204, 236];
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 shade(c: RGB, k: number): RGB { return [c[0] * k, c[1] * k, c[2] * k]; }
const canvasEl = root.querySelector('[data-role="canvas"]') as HTMLCanvasElement | null;
const pauseEl = root.querySelector('[data-role="pause"]') as HTMLButtonElement | null;
const ctxRaw = canvasEl ? canvasEl.getContext('2d') : null;
if (!canvasEl || !ctxRaw || !pauseEl) { return; }
const cv: HTMLCanvasElement = canvasEl;
const ctx: CanvasRenderingContext2D = ctxRaw;
const pauseBtn: HTMLButtonElement = pauseEl;
// 목표점(판 좌표)과 그 속도(px/초) — 8자 길 또는 포인터. 그리기에서 눈동자 방향·목표 표시에 쓴다
let tx = W / 2;
let ty = H / 2;
let tvx = 0;
let tvy = 0;
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(top: RGB, bottom: RGB): void {
const g = ctx.createLinearGradient(0, 0, 0, H);
g.addColorStop(0, rgba(top, 1));
g.addColorStop(1, rgba(bottom, 1));
ctx.fillStyle = g;
ctx.fillRect(0, 0, W, H);
}
// 점들을 지나는 매끈한 닫힌 곡선 — 이웃 두 점의 가운데를 잇고 점 자체는 2차 곡선의 조절점으로 쓴다
function smoothClosed(pts: number[]): void {
const n = pts.length / 2;
ctx.beginPath();
ctx.moveTo((pts[2 * (n - 1)] + pts[0]) / 2, (pts[2 * (n - 1) + 1] + pts[1]) / 2);
for (let i = 0; i < n; i += 1) {
const j = (i + 1) % n;
ctx.quadraticCurveTo(pts[2 * i], pts[2 * i + 1], (pts[2 * i] + pts[2 * j]) / 2, (pts[2 * i + 1] + pts[2 * j + 1]) / 2);
}
ctx.closePath();
}
function fillShape(pts: number[], fill: RGB, line: number): void {
smoothClosed(pts);
ctx.fillStyle = rgba(fill, 1);
ctx.fill();
if (line > 0) {
ctx.lineWidth = line;
ctx.lineJoin = 'round';
ctx.strokeStyle = rgba(INK, 1);
ctx.stroke();
}
}
// 바닥 그림자 — 같은 윤곽을 (ox, oy) 만큼 밀어 옅은 잉크색으로
function dropShadow(pts: number[], ox: number, oy: number, alpha: number): void {
ctx.save();
ctx.translate(ox, oy);
smoothClosed(pts);
ctx.fillStyle = rgba(INK, alpha);
ctx.fill();
ctx.restore();
}
// 눈 — 흰자 위 눈동자를 (lookX, lookY) 쪽으로 반지름의 0.4 만큼 민다. open 0~1 은 위 눈꺼풀이 덮는 정도의 반대
function drawEye(x: number, y: number, r: number, lookX: number, lookY: number, open: number): void {
const a = Math.atan2(lookY - y, lookX - x);
ctx.beginPath();
ctx.arc(x, y, r, 0, TAU);
ctx.fillStyle = rgba(CREAM, 1);
ctx.fill();
ctx.lineWidth = 1.5;
ctx.strokeStyle = rgba(INK, 1);
ctx.stroke();
ctx.beginPath();
ctx.arc(x + Math.cos(a) * r * 0.4, y + Math.sin(a) * r * 0.4, r * 0.55, 0, TAU);
ctx.fillStyle = rgba(INK, 1);
ctx.fill();
if (open < 1) {
ctx.save();
ctx.beginPath();
ctx.arc(x, y, r + 0.5, 0, TAU);
ctx.clip();
ctx.fillStyle = rgba(INK, 0.85);
ctx.fillRect(x - r - 1, y - r - 1, 2 * r + 2, (2 * r + 2) * (1 - open));
ctx.restore();
}
}
// 목표 표시 — 잉크색 고리와 점. 생물이 무엇을 쫓는지 보이게
function drawTarget(x: number, y: number): void {
// 동작 줄이기의 쉬는 자세에서는 포인터가 올라왔을 때만 보인다
if (still && !ptrOn) { return; }
ctx.beginPath();
ctx.arc(x, y, 7, 0, TAU);
ctx.lineWidth = 2;
ctx.strokeStyle = rgba(INK, 0.55);
ctx.stroke();
ctx.beginPath();
ctx.arc(x, y, 2.5, 0, TAU);
ctx.fillStyle = rgba(INK, 0.7);
ctx.fill();
}
// 06 해파리 — 갓이 PULSE_PERIOD 초마다 빠르게 오므리고(주기의 SQUEEZE_SHARE) 천천히 편다.
// 오므리는 만큼(수축량의 증가분) 갓이 향한 쪽으로 PULSE_IMPULSE(px/초)를 받고, 물의 저항 WATER_DRAG(1/초)로 속도가 줄어든다
const PULSE_PERIOD = 1.2;
const SQUEEZE_SHARE = 0.3;
const PULSE_IMPULSE = 160;
const WATER_DRAG = 1.6;
// 갓이 1초에 도는 각(라디안) — 목표 쪽으로 천천히 고개를 튼다
const JELLY_TURN = 2.4;
// 갓이 가장 오므렸을 때 폭이 줄어드는 비율
const SQUEEZE_DEPTH = 0.3;
const JELLY_MARGIN = 55;
// 촉수 — 갓 가장자리에 TENTACLE_COUNT 개, 마디 TENTACLE_LINKS 개, 간격 LINK_GAP(px).
// 마디마다 직전 위치와의 차이(관성)에 TRAIL_KEEP 을 곱해 이어 가고 아래로 SINK(px/초²) 만큼 가라앉은 뒤, 간격 맞추기를 LINK_PASSES 번 되풀이한다
const TENTACLE_COUNT = 5;
const TENTACLE_LINKS = 10;
const LINK_GAP = 11;
const TRAIL_KEEP = 0.92;
const SINK = 30;
const LINK_PASSES = 3;
const PREWARM = 3;
function pathAt(t: number): Pt { return figureEight(t, 170, 85, 10); }
type Jelly = { x: number; y: number; vx: number; vy: number; heading: number; phase: number; squeeze: number; size: number; lag: number; xs: Float64Array[]; ys: Float64Array[]; pxs: Float64Array[]; pys: Float64Array[] };
function makeJelly(size: number, lag: number, phase: number): Jelly {
const j: Jelly = { x: 0, y: 0, vx: 0, vy: 0, heading: -Math.PI / 2, phase: phase, squeeze: 0, size: size, lag: lag, xs: [], ys: [], pxs: [], pys: [] };
for (let k = 0; k < TENTACLE_COUNT; k += 1) {
j.xs.push(new Float64Array(TENTACLE_LINKS));
j.ys.push(new Float64Array(TENTACLE_LINKS));
j.pxs.push(new Float64Array(TENTACLE_LINKS));
j.pys.push(new Float64Array(TENTACLE_LINKS));
}
return j;
}
const jellies: Jelly[] = [makeJelly(40, 0, 0), makeJelly(27, 3.4, 0.45)];
let jellyClock = 0;
// 수축량 0~1 — 주기 앞 SQUEEZE_SHARE 동안 빠르게 0→1, 나머지 동안 천천히 1→0
function squeezeAt(phase: number): number {
const u = phase - Math.floor(phase);
return u < SQUEEZE_SHARE ? smooth(u / SQUEEZE_SHARE) : 1 - smooth((u - SQUEEZE_SHARE) / (1 - SQUEEZE_SHARE));
}
// 촉수 뿌리 — 갓 뒤쪽 가장자리를 따라 고르게. 갓이 오므리면 폭과 함께 좁아진다
function rimOf(j: Jelly, k: number): Pt {
const back = j.heading + Math.PI;
const across = (k / (TENTACLE_COUNT - 1) - 0.5) * 1.6 * j.size * (1 - SQUEEZE_DEPTH * j.squeeze);
return [j.x + Math.cos(back) * j.size * 0.25 + Math.cos(j.heading + Math.PI / 2) * across, j.y + Math.sin(back) * j.size * 0.25 + Math.sin(j.heading + Math.PI / 2) * across];
}
function hangTentacles(j: Jelly): void {
for (let k = 0; k < TENTACLE_COUNT; k += 1) {
const r = rimOf(j, k);
for (let i = 0; i < TENTACLE_LINKS; i += 1) {
j.xs[k][i] = r[0];
j.ys[k][i] = r[1] + i * LINK_GAP;
j.pxs[k][i] = j.xs[k][i];
j.pys[k][i] = j.ys[k][i];
}
}
}
// 촉수 한 걸음 — 관성(직전 위치와의 차 × TRAIL_KEEP) + 가라앉기(SINK × dt²), 뿌리는 갓에 고정, 간격 맞추기 LINK_PASSES 번
function stepTentacle(xs: Float64Array, ys: Float64Array, pxs: Float64Array, pys: Float64Array, rx: number, ry: number, dt: number, passes: number): void {
for (let i = 1; i < TENTACLE_LINKS; i += 1) {
const nx = xs[i] + (xs[i] - pxs[i]) * TRAIL_KEEP;
const ny = ys[i] + (ys[i] - pys[i]) * TRAIL_KEEP + SINK * dt * dt;
pxs[i] = xs[i];
pys[i] = ys[i];
xs[i] = nx;
ys[i] = ny;
}
xs[0] = rx;
ys[0] = ry;
pxs[0] = rx;
pys[0] = ry;
for (let p = 0; p < passes; p += 1) {
for (let i = 1; i < TENTACLE_LINKS; i += 1) {
const dx = xs[i] - xs[i - 1];
const dy = ys[i] - ys[i - 1];
const d = Math.hypot(dx, dy) || 1;
const diff = (d - LINK_GAP) / d;
// 뿌리 쪽 첫 마디는 뿌리가 고정이라 혼자 다 움직이고, 나머지는 둘이 반씩
if (i === 1) {
xs[i] -= dx * diff;
ys[i] -= dy * diff;
} else {
xs[i - 1] += dx * diff * 0.5;
ys[i - 1] += dy * diff * 0.5;
xs[i] -= dx * diff * 0.5;
ys[i] -= dy * diff * 0.5;
}
}
}
}
function stepJelly(j: Jelly, dt: number, gx: number, gy: number): void {
const want = Math.atan2(gy - j.y, gx - j.x);
j.heading = wrapAngle(j.heading + clamp(wrapAngle(want - j.heading), -JELLY_TURN * dt, JELLY_TURN * dt));
j.phase += dt / PULSE_PERIOD;
const before = j.squeeze;
j.squeeze = squeezeAt(j.phase);
const push = Math.max(0, j.squeeze - before) * PULSE_IMPULSE;
j.vx += Math.cos(j.heading) * push;
j.vy += Math.sin(j.heading) * push;
const drag = Math.exp(-WATER_DRAG * dt);
j.vx *= drag;
j.vy *= drag;
j.x += j.vx * dt;
j.y += j.vy * dt;
// 판 가장자리 — JELLY_MARGIN(px) 안으로 들어오면 넘친 거리 × 4 만큼 안쪽으로 속도를 돌려 판 밖으로 나가지 않게
const ox = j.x < JELLY_MARGIN ? JELLY_MARGIN - j.x : (j.x > W - JELLY_MARGIN ? W - JELLY_MARGIN - j.x : 0);
const oy = j.y < JELLY_MARGIN ? JELLY_MARGIN - j.y : (j.y > H - JELLY_MARGIN ? H - JELLY_MARGIN - j.y : 0);
j.vx += ox * 4 * dt;
j.vy += oy * 4 * dt;
for (let k = 0; k < TENTACLE_COUNT; k += 1) {
const r = rimOf(j, k);
stepTentacle(j.xs[k], j.ys[k], j.pxs[k], j.pys[k], r[0], r[1], dt, LINK_PASSES);
}
}
function reset(): void {
jellyClock = 0;
for (let n = 0; n < jellies.length; n += 1) {
const j = jellies[n];
const p = pathAt(-j.lag);
j.x = p[0];
j.y = p[1] + 30;
j.vx = 0;
j.vy = 0;
j.heading = -Math.PI / 2;
j.phase = n * 0.45;
j.squeeze = squeezeAt(j.phase);
hangTentacles(j);
}
}
// 큰 해파리는 목표를, 작은 해파리는 같은 8자 길을 lag 초 늦게 쫓는다
function update(dt: number, tx: number, ty: number, tvx: number, tvy: number): void {
jellyClock += dt;
for (let n = 0; n < jellies.length; n += 1) {
const j = jellies[n];
if (j.lag === 0) {
stepJelly(j, dt, tx, ty);
} else {
const p = pathAt(jellyClock - j.lag);
stepJelly(j, dt, p[0], p[1]);
}
}
}
// 쉬는 자세 — 두 마리 모두 위를 보고 촉수를 곧게 늘어뜨린 채 반쯤 편 갓
function restPose(): void {
const spots: number[] = [W / 2 - 60, H / 2 - 40, W / 2 + 110, H / 2 - 10];
for (let n = 0; n < jellies.length; n += 1) {
const j = jellies[n];
j.x = spots[n * 2];
j.y = spots[n * 2 + 1];
j.heading = -Math.PI / 2;
j.squeeze = 0.3;
hangTentacles(j);
}
}
// 물빛 바탕 — 위는 옅은 라벤더, 아래는 옅은 하늘색
const SEA_TOP: RGB = [238, 234, 250];
const SEA_LOW: RGB = [218, 236, 246];
function drawJelly(j: Jelly, bell: RGB, frill: RGB): void {
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
// 촉수 물결 — 박동 위상을 따라 갓 옆 방향으로 흔든다. 끝으로 갈수록(i 가 클수록) 크게
const nx = Math.cos(j.heading + Math.PI / 2);
const ny = Math.sin(j.heading + Math.PI / 2);
for (let k = 0; k < TENTACLE_COUNT; k += 1) {
for (let pass = 0; pass < 2; pass += 1) {
ctx.beginPath();
ctx.moveTo(j.xs[k][0], j.ys[k][0]);
for (let i = 1; i < TENTACLE_LINKS; i += 1) {
const wob = Math.sin(j.phase * TAU - i * 0.8 + k * 1.3) * i * 0.7 * j.size / 40;
ctx.lineTo(j.xs[k][i] + nx * wob, j.ys[k][i] + ny * wob);
}
ctx.lineWidth = (pass === 0 ? 5 : 2.6) * j.size / 40;
ctx.strokeStyle = pass === 0 ? rgba(INK, 0.9) : rgba(frill, 1);
ctx.stroke();
}
}
// 갓 — 진행 방향이 위가 되게 돌린 좌표에서 반타원 지붕 + 물결 가장자리. 오므릴수록 좁고 길어진다
const w = j.size * (1 - SQUEEZE_DEPTH * j.squeeze);
const h = j.size * 0.85 * (1 + 0.35 * j.squeeze);
const base = j.size * 0.25;
ctx.save();
ctx.translate(j.x, j.y);
ctx.rotate(j.heading + Math.PI / 2);
ctx.beginPath();
ctx.ellipse(0, base, w, h, 0, Math.PI, TAU);
const lumps = 6;
for (let s = 0; s < lumps; s += 1) {
const x0 = w - 2 * w * s / lumps;
const x1 = w - 2 * w * (s + 1) / lumps;
ctx.quadraticCurveTo((x0 + x1) / 2, base + j.size * 0.16, x1, base);
}
ctx.closePath();
ctx.fillStyle = rgba(bell, 0.94);
ctx.fill();
ctx.lineWidth = 2.4;
ctx.strokeStyle = rgba(INK, 1);
ctx.stroke();
// 속 무늬 — 갓 안쪽 네 잎. 갓 크기를 따라 줄고 는다
ctx.fillStyle = rgba(frill, 0.9);
for (let p = 0; p < 4; p += 1) {
const px = (p - 1.5) * w * 0.34;
ctx.beginPath();
ctx.ellipse(px, base - h * 0.42, w * 0.13, h * 0.24, (p - 1.5) * 0.25, 0, TAU);
ctx.fill();
}
// 하이라이트 — 지붕 왼쪽 위에 크림색 호
ctx.beginPath();
ctx.ellipse(-w * 0.35, base - h * 0.62, w * 0.22, h * 0.12, -0.5, 0, TAU);
ctx.fillStyle = rgba(CREAM, 0.85);
ctx.fill();
ctx.restore();
}
function draw(): void {
clearStage(SEA_TOP, SEA_LOW);
drawJelly(jellies[1], PINK, LAVENDER);
drawJelly(jellies[0], LAVENDER, PINK);
for (let s = -1; s <= 1; s += 2) {
const j = jellies[0];
const ex = j.x + Math.cos(j.heading + Math.PI / 2) * s * 10 - Math.cos(j.heading) * 2;
const ey = j.y + Math.sin(j.heading + Math.PI / 2) * s * 10 - Math.sin(j.heading) * 2;
drawEye(ex, ey, 4.5, tx, ty, 1);
}
drawTarget(tx, ty);
}
// 한 프레임에 넘기는 시간 상한(초) — 탭을 오래 숨겼다 돌아온 첫 프레임에도 50ms 까지만 계산에 넣는다
const DT_MAX = 0.05;
// 미리 돌리기 — 첫 장면을 그리기 전에 PREWARM 초를 1/60초 걸음으로 계산해 생물이 길 위에 자리 잡은 채 시작한다
const PREWARM_STEP = 1 / 60;
// 시연 시계(초) — 8자 길 위의 자리를 정한다
let simTime = 0;
// 포인터(판 좌표) — 판 위에 있으면 목표를 포인터 쪽으로 옮긴다. 떠나면 다시 8자 길로 서서히 돌아간다
let ptrX = W / 2;
let ptrY = H / 2;
let ptrOn = false;
let ptrBlend = 0;
let paused = false;
const reduceQuery = window.matchMedia('(prefers-reduced-motion: reduce)');
// 페이지를 연 채 동작 줄이기 설정을 바꿔도 change 리스너가 이 값을 다시 읽는다
let still = reduceQuery.matches;
// 자동 시연 중인가 — 사람이 처음 손대면 시연 표시를 떼고 알림 줄을 polite 로 켠다
let demo = root.classList.contains('is-demo');
// 리스너는 한 묶음으로 달고 정리할 때 한 번에 뗀다
const off = new AbortController();
function wake(): void {
if (!demo) { return; }
demo = false;
root.classList.remove('is-demo');
const live = root.querySelector('[aria-live]');
if (live) { live.setAttribute('aria-live', 'polite'); }
}
// 목표 옮기기 — 8자 길 자리와 포인터 자리를 ptrBlend 비율로 섞고, 그 변화로 목표 속도를 잰다
function moveTarget(dt: number): void {
const p = pathAt(simTime);
ptrBlend = lerp(ptrBlend, ptrOn ? 1 : 0, follow(4, dt));
const nx = lerp(p[0], ptrX, ptrBlend);
const ny = lerp(p[1], ptrY, ptrBlend);
if (dt > 0) {
tvx = lerp(tvx, (nx - tx) / dt, follow(12, dt));
tvy = lerp(tvy, (ny - ty) / dt, follow(12, dt));
}
tx = nx;
ty = ny;
}
function advance(dt: number): void {
simTime += dt;
moveTarget(dt);
update(dt, tx, ty, tvx, tvy);
}
let rafId = 0;
let lastTs = -1;
function frame(ts: number): void {
if (still || paused) { rafId = 0; return; }
if (lastTs < 0) { lastTs = ts; }
const dt = Math.min((ts - lastTs) / 1000, DT_MAX);
lastTs = ts;
if (dt > 0) { advance(dt); }
draw();
rafId = window.requestAnimationFrame(frame);
}
function startLoop(): void {
if (rafId) { return; }
// 시계 다시 맞추기 — 멈췄던 사이의 시간을 첫 프레임 dt 로 넘기지 않는다
lastTs = -1;
rafId = window.requestAnimationFrame(frame);
}
function stopLoop(): void {
if (rafId) { window.cancelAnimationFrame(rafId); rafId = 0; }
}
// 동작 줄이기 — 루프를 돌리지 않고 쉬는 자세 한 장면만 그린다
function showRest(): void {
stopLoop();
reset();
restPose();
draw();
}
function play(): void {
reset();
simTime = 0;
const p = pathAt(0);
tx = p[0];
ty = p[1];
tvx = 0;
tvy = 0;
for (let t = 0; t < PREWARM; t += PREWARM_STEP) { advance(PREWARM_STEP); }
draw();
if (!paused) { startLoop(); }
}
function setPointer(ev: PointerEvent): void {
const r = cv.getBoundingClientRect();
ptrX = (ev.clientX - r.left) * W / Math.max(1, r.width);
ptrY = (ev.clientY - r.top) * H / Math.max(1, r.height);
ptrOn = true;
wake();
// 동작 줄이기에서도 입력은 화면에 남는다 — 쉬는 자세 그대로 눈과 목표 표시만 포인터 쪽으로 다시 그린다
if (still) {
tx = ptrX;
ty = ptrY;
draw();
}
}
cv.addEventListener('pointermove', setPointer, { signal: off.signal });
cv.addEventListener('pointerdown', setPointer, { signal: off.signal });
function leavePointer(): void { ptrOn = false; }
cv.addEventListener('pointerleave', leavePointer, { signal: off.signal });
cv.addEventListener('pointercancel', leavePointer, { signal: off.signal });
pauseBtn.addEventListener('click', function (): void {
paused = !paused;
pauseBtn.setAttribute('aria-pressed', paused ? 'true' : 'false');
wake();
if (paused) { stopLoop(); } else if (!still) { startLoop(); }
}, { signal: off.signal });
// 탭이 숨으면 루프를 멈추고, 돌아오면 시계를 다시 맞춰 시작한다 — 숨은 동안의 몇 초가 한 프레임에 몰리지 않게
document.addEventListener('visibilitychange', function (): void {
if (document.hidden) { stopLoop(); } else if (!paused && !still) { startLoop(); }
}, { signal: off.signal });
// 설정이 페이지를 연 채 바뀌면 — 켜지면 쉬는 자세로 멈추고, 꺼지면 시연을 처음부터
reduceQuery.addEventListener('change', function (): void {
still = reduceQuery.matches;
if (still) { showRest(); } else { play(); }
}, { signal: off.signal });
window.addEventListener('resize', function (): void {
fitCanvas();
draw();
}, { signal: off.signal });
fitCanvas();
if (still) { showRest(); } else { play(); }
return function (): void {
stopLoop();
off.abort();
};
}, []);
return (
<div className={cx("cf") + " is-demo"} ref={rootRef}>
<canvas className={cx("cf__canvas")} data-role="canvas" width={480} height={300} role="img" aria-label="갓을 오므릴 때마다 앞으로 밀려 나가고 촉수가 뒤따라 흔들리는 해파리 두 마리."></canvas>
<button className={cx("cf__pause")} data-role="pause" type="button" aria-pressed="false">{'일시정지'}</button>
</div>
);
}06 A Jellyfish That Lurches Forward Each Time Its Bell Squeezes — Measured area 17.967% · moving frames 23/23Original by GODRICH · SCSS and React ship in the zip · Cursor Follow Animation: 9 Procedural Creatures
The post this demo lives in
Cursor Follow Animation: 9 Procedural CreaturesIn a cursor follow animation, with no joint keyframed, how does a creature swim and walk after a target? 01 keeps only t See all demos in this post
If you like this effect - similar demos
Interactions01 Icon-morph check — a button that draws its success as a single stroke9 Copy Button CSS UI Patterns (Copy to Clipboard)
Interactions05 Intersection reveal — an element that appears once its visibility ratio crosses a thresholdMicro Interactions: 9 Essential UI Patterns
Interactions08 A Bubble That Mirrors Sky and Window, Reflecting More Toward Its EdgeBubble Animation CSS: 9 Soap-Film Scenes That Pop