07A Button Label Whose Letters Scatter One by One and Regather as Sent
Each letter gets its own direction and distance from seeded noise and scatters on a stagger, while the new letters spring into place and the button width is interpolated along with them.
Best forComment posts and feedback sends
LETTER_STAGGER_MSSCATTER_AMPREGATHER_MS

<main class="stage">
<div class="sb is-demo" id="sb">
<div class="sb__scene" data-role="scene">
<span class="lt__box" aria-hidden="true"><span class="lt__line"></span><span class="lt__line lt__line--short"></span></span>
<button class="lt__send" data-role="send" type="button">
<span class="lt__pill" aria-hidden="true">
<span class="lt__mid" data-role="mid"></span>
<span class="lt__cap" data-role="capl"></span>
<span class="lt__cap" data-role="capr"></span>
</span>
<span class="lt__letters" data-role="letters" data-glyph="lt__glyph"></span>
</button>
<p class="sb__status" data-role="status" aria-live="off">Ready to post</p>
</div>
</div>
</main>@use "../../../../site/static/demo-tokens" as *;
@include stage($stage-ink);
.sb {
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;
}
// 장면 판 — 480×300 좌표로 짜 두고 스크립트가 상자 폭에 맞춰 scale 한다.
// 기준점이 왼쪽 위 모서리인 이유: 판이 상자 왼쪽 위에 붙어 있어 모서리 기준으로 줄여야 줄인 판이 상자와 겹친다
.sb__scene {
position: absolute;
left: 0;
top: 0;
width: 480px;
height: 300px;
transform-origin: 0 0;
}
.sb__canvas {
position: absolute;
left: 0;
top: 0;
width: 480px;
height: 300px;
pointer-events: none;
}
.sb__status {
position: absolute;
left: $sp-4;
bottom: $sp-3;
box-sizing: border-box;
max-width: 260px;
margin: 0;
padding: $sp-1 $sp-3;
border-radius: $r-pill;
background: rgba(255, 255, 255, .9);
color: $subject-ink;
font-weight: 500;
font-size: 12px;
line-height: 1.4;
pointer-events: none;
}
.sb__status--top {
top: $sp-3;
bottom: auto;
}
.sb__status--side {
max-width: 140px;
border-radius: $r-control;
}
.sb { background: #eaf6f1; }
.lt__box {
position: absolute;
left: 100px;
top: 36px;
width: 280px;
height: 64px;
box-sizing: border-box;
padding: $sp-4;
border-radius: $r-sm;
background: #ffffff;
box-shadow: inset 0 0 0 1px rgba(23, 20, 26, .08);
display: flex;
flex-direction: column;
gap: $sp-2;
}
.lt__line {
display: block;
height: 8px;
border-radius: $r-pill;
background: #e3ece8;
}
.lt__line--short { width: 55%; }
// 버튼 판 = 가운데 x 240 기준. 너비는 스크립트가 두 문구 중 긴 쪽에 맞춰 한 번 정한다
.lt__send {
position: absolute;
left: 100px;
top: 128px;
width: 280px;
height: 52px;
margin: 0;
padding: 0;
border: 0;
border-radius: $r-pill;
background: none;
color: $subject-ink;
font: inherit;
cursor: pointer;
}
.lt__send:focus-visible {
outline: 3px solid $subject-ink;
outline-offset: 3px;
}
// 알약 = 가운데 몸통(scaleX) + 양끝 반원 두 개(translateX). 셋 다 판 가운데에 겹쳐 두고 스크립트가 벌린다
.lt__pill {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
pointer-events: none;
}
.lt__mid,
.lt__cap {
position: absolute;
top: 0;
height: 52px;
background: #b4ecd9;
}
.lt__mid {
left: calc(50% - 50px);
width: 100px;
}
.lt__cap {
left: calc(50% - 26px);
width: 52px;
border-radius: 50%;
}
.lt__letters {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
pointer-events: none;
}
.lt__glyph {
display: inline-block;
font-weight: 700;
font-size: 17px;
line-height: 1;
white-space: pre;
}
@media (max-width: 340px) {
// 이 폭에서는 장면이 0.6 배 남짓으로 줄어든다 — 상태 줄 글자를 키워 줄인 뒤에도 읽히게 한다
.sb__status { font-size: 16px; }
}
@media (prefers-reduced-motion: reduce) {
// 움직임은 전부 스크립트가 그리고, 스크립트는 reduce 에서 루프를 돌리지 않고 결과 상태만 둔다. CSS 쪽 전환도 막아 둔다
.sb__scene * {
transition: none !important;
animation: 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);
}
.sb {
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);
}
.sb__scene {
position: absolute;
left: 0;
top: 0;
width: 480px;
height: 300px;
transform-origin: 0 0;
}
.sb__canvas {
position: absolute;
left: 0;
top: 0;
width: 480px;
height: 300px;
pointer-events: none;
}
.sb__status {
position: absolute;
left: 16px;
bottom: 12px;
box-sizing: border-box;
max-width: 260px;
margin: 0;
padding: 4px 12px;
border-radius: 999px;
background: rgba(255, 255, 255, 0.9);
color: #17141a;
font-weight: 500;
font-size: 12px;
line-height: 1.4;
pointer-events: none;
}
.sb__status--top {
top: 12px;
bottom: auto;
}
.sb__status--side {
max-width: 140px;
border-radius: 12px;
}
.sb {
background: #eaf6f1;
}
.lt__box {
position: absolute;
left: 100px;
top: 36px;
width: 280px;
height: 64px;
box-sizing: border-box;
padding: 16px;
border-radius: 8px;
background: #ffffff;
box-shadow: inset 0 0 0 1px rgba(23, 20, 26, 0.08);
display: flex;
flex-direction: column;
gap: 8px;
}
.lt__line {
display: block;
height: 8px;
border-radius: 999px;
background: #e3ece8;
}
.lt__line--short {
width: 55%;
}
.lt__send {
position: absolute;
left: 100px;
top: 128px;
width: 280px;
height: 52px;
margin: 0;
padding: 0;
border: 0;
border-radius: 999px;
background: none;
color: #17141a;
font: inherit;
cursor: pointer;
}
.lt__send:focus-visible {
outline: 3px solid #17141a;
outline-offset: 3px;
}
.lt__pill {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
pointer-events: none;
}
.lt__mid,
.lt__cap {
position: absolute;
top: 0;
height: 52px;
background: #b4ecd9;
}
.lt__mid {
left: calc(50% - 50px);
width: 100px;
}
.lt__cap {
left: calc(50% - 26px);
width: 52px;
border-radius: 50%;
}
.lt__letters {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
pointer-events: none;
}
.lt__glyph {
display: inline-block;
font-weight: 700;
font-size: 17px;
line-height: 1;
white-space: pre;
}
@media (max-width: 340px) {
.sb__status {
font-size: 16px;
}
}
@media (prefers-reduced-motion: reduce) {
.sb__scene * {
transition: none !important;
animation: none !important;
}
}(function () {
const root = document.getElementById("sb");
if (!root) return;
const W = 480;
const H = 300;
const FIXED_DT = 16;
// 파스텔 팔레트 — 캔버스와 스크립트가 칠하는 색은 여기서만 고른다 (scss 쪽 색은 demo-tokens)
const INK = [38, 33, 52];
const PAPER = [255, 252, 246];
const CREAM = [255, 243, 224];
const SKY = [158, 208, 255];
const LILAC = [200, 184, 255];
const MINT = [156, 228, 204];
const PINK = [255, 182, 204];
const PEACH = [255, 214, 184];
function clamp(v, lo, hi) { return v < lo ? lo : (v > hi ? hi : v); }
function lerp(a, b, t) { return a + (b - a) * t; }
function easeOut(x) { const c = clamp(x, 0, 1); return 1 - Math.pow(1 - c, 3); }
function easeInOut(x) {
const c = clamp(x, 0, 1);
return c < 0.5 ? 4 * c * c * c : 1 - Math.pow(-2 * c + 2, 3) / 2;
}
function rgba(c, a) {
return 'rgba(' + Math.round(c[0]) + ',' + Math.round(c[1]) + ',' + Math.round(c[2]) + ',' + clamp(a, 0, 1).toFixed(3) + ')';
}
function mix(a, b, t) { return [lerp(a[0], b[0], t), lerp(a[1], b[1], t), lerp(a[2], b[2], t)]; }
// 시드 고정 난수 — 같은 시드면 같은 값이 다시 나온다 (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;
};
}
const sceneEl = root.querySelector('[data-role="scene"]');
const statusEl = root.querySelector('[data-role="status"]');
if (!sceneEl || !statusEl) {
return;
}
const scene = sceneEl;
const status = statusEl;
const reduceQuery = window.matchMedia('(prefers-reduced-motion: reduce)');
const still = reduceQuery.matches;
const resizeHooks = [];
// 자동 시연 중인가 — 사람이 처음 만지는 순간 시연을 멈추고 처음 상태로 돌린 뒤 상태 줄을 읽어 주기 시작한다
let demo = root.classList.contains('is-demo');
function wake() {
if (!demo) {
return;
}
demo = false;
root.classList.remove('is-demo');
status.setAttribute('aria-live', 'polite');
resetIdle();
}
function say(text) {
if (status.textContent !== text) {
status.textContent = text;
}
}
// 장면 배율 — 480×300 좌표로 짠 판을 상자 폭에 맞춰 통째로 줄인다
let k = 1;
function fitScene() {
const w = root.clientWidth;
k = w > 0 ? w / W : 1;
scene.style.transform = 'scale(' + k.toFixed(4) + ')';
}
// 화면 좌표(CSS px) → 장면 좌표(480×300). 줄인 배율 k 로 나눠야 판 안의 위치가 된다
function toScene(clientX, clientY) {
const r = root.getBoundingClientRect();
return [(clientX - r.left) / k, (clientY - r.top) / k];
}
// 캡처 단계에서 듣는다 — 버튼 자신의 pointerdown 보다 먼저 시연을 끝내야 사람의 첫 누름이 처음 상태에서 시작한다
root.addEventListener('pointerdown', wake, true);
root.addEventListener('keydown', wake, true);
// 2D 값 노이즈 — 격자점마다 시드 난수 값을 두고 사이를 부드럽게 보간한다. 결과는 -1~1
function makeNoise(seed) {
const rng = makeRng(seed);
const perm = new Uint8Array(512);
const vals = new Float32Array(256);
for (let i = 0; i < 256; i += 1) {
vals[i] = rng() * 2 - 1;
perm[i] = i;
}
for (let i = 255; i > 0; i -= 1) {
const j = Math.floor(rng() * (i + 1));
const t = perm[i];
perm[i] = perm[j];
perm[j] = t;
}
for (let i = 0; i < 256; i += 1) {
perm[i + 256] = perm[i];
}
function at(xi, yi) { return vals[perm[(xi & 255) + perm[yi & 255]]]; }
return function (x, y) {
const xi = Math.floor(x);
const yi = Math.floor(y);
const fx = x - xi;
const fy = y - yi;
const u = fx * fx * (3 - 2 * fx);
const v = fy * fy * (3 - 2 * fy);
const a = lerp(at(xi, yi), at(xi + 1, yi), u);
const b = lerp(at(xi, yi + 1), at(xi + 1, yi + 1), u);
return lerp(a, b, v);
};
}
const BTN_H = 52;
// 알약 가운데 몸통의 기준 너비(px) — scaleX 로 늘이고 양끝 반원은 따로 옮긴다
const MID_BASE = 100;
const PAD_X = 28;
// 글자 사이 출발 시차
const LETTER_STAGGER_MS = 34;
// 흩어지는 거리(px) — 글자마다 노이즈로 0.55~1 배
const SCATTER_AMP = 46;
// 새 글자가 스프링으로 제자리에 드는 시간 — 흔들림 폭이 처음의 3% 밑으로 줄어드는 시각
const REGATHER_MS = 520;
const REGATHER_ZETA = 0.42;
const REGATHER_DELAY = 140;
const SCATTER_MS = 360;
const DEMO_CYCLE = 2000;
const TXT_IDLE = 'Post comment';
const TXT_SENT = 'Sent';
const TXT_READY = 'Ready to post';
const TXT_SWAP = 'Scattering and regathering the letters';
const TXT_DONE = 'Sent — your comment is up';
const TXT_BACK = 'Ready for a new comment';
const sendEl = root.querySelector('[data-role="send"]');
const lettersEl = root.querySelector('[data-role="letters"]');
const capLEl = root.querySelector('[data-role="capl"]');
const capREl = root.querySelector('[data-role="capr"]');
const midEl = root.querySelector('[data-role="mid"]');
if (!sendEl || !lettersEl || !capLEl || !capREl || !midEl) {
return;
}
const send = sendEl;
const letters = lettersEl;
const capL = capLEl;
const capR = capREl;
const mid = midEl;
const noise = makeNoise(466);
// 스프링 감쇠 곡선의 두 값 — REGATHER_MS 에 폭이 3% 가 되게 감쇠율을 정하고, 감쇠비로 진동수를 낸다
const decayRate = Math.log(1 / 0.03) / REGATHER_MS;
const omegaD = (decayRate / REGATHER_ZETA) * Math.sqrt(1 - REGATHER_ZETA * REGATHER_ZETA);
let phase = 'idle';
let pt = 0;
let sent = false;
let oldGlyphs = [];
let newGlyphs = [];
let w0 = 0;
let w1 = 0;
let demoNext = 200;
// 남은 변위 비율 — 1 에서 시작해 진동하며 0 으로. 감쇠 사인(코사인) 하나로 스프링 해를 그린다
function springLeft(t) {
if (t <= 0) {
return 1;
}
return Math.exp(-decayRate * t) * Math.cos(omegaD * t);
}
// 글자 i 의 흩어질 방향·거리·회전 — 같은 시드면 같은 글자는 같은 쪽으로 난다
function scatterOf(i, row) {
const a = -Math.PI / 2 + noise(i * 0.61, row) * Math.PI * 0.9;
const d = SCATTER_AMP * (0.55 + 0.45 * (noise(i * 0.61, row + 7.3) * 0.5 + 0.5));
return [Math.cos(a) * d, Math.sin(a) * d, noise(i * 0.61, row + 13.1) * 40];
}
function makeLayer(text, row) {
const out = [];
Array.from(text).forEach(function (ch, i) {
const s = document.createElement('span');
s.className = letters.getAttribute('data-glyph') || '';
s.textContent = ch === ' ' ? ' ' : ch;
letters.appendChild(s);
const v = scatterOf(i, row);
out.push({ el: s, ox: v[0], oy: v[1], rot: v[2] });
});
return out;
}
function layerWidth(gs) {
let w = 0;
for (const g of gs) {
w += g.el.getBoundingClientRect().width / k;
}
return w > 0 ? w : gs.length * 14;
}
// 알약 너비 w — 양끝 반원은 ±(w/2 − 높이/2) 로 옮기고 가운데만 scaleX 로 늘인다(모서리가 늘어나 찌그러지지 않는다)
function setPill(w) {
const half = Math.max(0, w / 2 - BTN_H / 2);
capL.style.transform = 'translateX(' + (-half).toFixed(2) + 'px)';
capR.style.transform = 'translateX(' + half.toFixed(2) + 'px)';
mid.style.transform = 'scaleX(' + ((half * 2) / MID_BASE).toFixed(4) + ')';
}
function clearLetters() {
while (letters.firstChild) {
letters.removeChild(letters.firstChild);
}
}
function showLabel(text) {
clearLetters();
oldGlyphs = makeLayer(text, 0.5);
w0 = layerWidth(oldGlyphs) + PAD_X * 2;
setPill(w0);
send.setAttribute('aria-label', text);
}
// 버튼 판 너비 — 두 문구 중 긴 쪽 알약에 맞춰 한 번 정한다(포커스 테두리가 알약을 감싸게). 가운데 x 240 은 그대로
function fitButton() {
const probe = makeLayer(TXT_SENT, 9.9);
const w = Math.ceil(Math.max(layerWidth(probe) + PAD_X * 2, w0));
for (const g of probe) {
letters.removeChild(g.el);
}
send.style.width = w + 'px';
send.style.left = (W / 2 - w / 2).toFixed(1) + 'px';
}
function resetIdle() {
phase = 'idle';
pt = 0;
sent = false;
newGlyphs = [];
showLabel(TXT_IDLE);
fitButton();
say(TXT_READY);
}
function finish() {
phase = 'done';
pt = 0;
showLabel(sent ? TXT_SENT : TXT_IDLE);
say(sent ? TXT_DONE : TXT_BACK);
}
function settle() {
sent = true;
finish();
}
function press() {
if (phase === 'swap') {
return;
}
sent = !sent;
if (still) {
finish();
return;
}
const next = sent ? TXT_SENT : TXT_IDLE;
for (const g of oldGlyphs) {
g.el.setAttribute('aria-hidden', 'true');
}
newGlyphs = makeLayer(next, 3.7);
w1 = layerWidth(newGlyphs) + PAD_X * 2;
send.setAttribute('aria-label', next);
phase = 'swap';
pt = 0;
say(TXT_SWAP);
}
function swapEnd() {
return REGATHER_DELAY + newGlyphs.length * LETTER_STAGGER_MS + REGATHER_MS;
}
function step() {
if (phase !== 'swap') {
return;
}
pt += FIXED_DT;
if (pt >= swapEnd()) {
finish();
}
}
function demoTick(t) {
if (t < demoNext) {
return;
}
demoNext += DEMO_CYCLE;
if (phase === 'swap') {
finish();
}
press();
}
function draw() {
if (phase !== 'swap') {
return;
}
oldGlyphs.forEach(function (g, i) {
const p = clamp((pt - i * LETTER_STAGGER_MS) / SCATTER_MS, 0, 1);
const e = easeOut(p);
g.el.style.transform = 'translate(' + (g.ox * e).toFixed(2) + 'px,' + (g.oy * e + 18 * p * p).toFixed(2) + 'px) rotate(' + (g.rot * e).toFixed(1) + 'deg)';
g.el.style.opacity = (1 - p).toFixed(3);
});
newGlyphs.forEach(function (g, j) {
const tau = pt - REGATHER_DELAY - j * LETTER_STAGGER_MS;
const f = springLeft(tau);
// 새 글자는 흩어질 방향의 반대편에서 들어온다
g.el.style.transform = 'translate(' + (-g.ox * f).toFixed(2) + 'px,' + (-g.oy * f).toFixed(2) + 'px) rotate(' + (-g.rot * f).toFixed(1) + 'deg)';
g.el.style.opacity = clamp(tau / 120, 0, 1).toFixed(3);
});
// 너비도 같은 스프링 곡선으로 — 새 너비를 살짝 지나쳤다가 돌아온다
setPill(w1 + (w0 - w1) * springLeft(pt - REGATHER_DELAY));
}
send.addEventListener('click', function () { press(); });
resetIdle();
let rafId = 0;
let lastTs = -1;
let acc = 0;
let clock = 0;
function onResize() {
fitScene();
for (const f of resizeHooks) {
f();
}
draw();
}
fitScene();
window.addEventListener('resize', onResize);
function frame(ts) {
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;
if (demo) {
demoTick(clock);
}
step();
acc -= FIXED_DT;
n += 1;
}
draw();
rafId = window.requestAnimationFrame(frame);
}
if (still) {
settle();
draw();
}
else {
rafId = window.requestAnimationFrame(frame);
}
return function () {
window.cancelAnimationFrame(rafId);
window.removeEventListener('resize', onResize);
};
})();// SendLabelLetterScatter - vanilla 판(07-send-btn-label-letter-scatter) 의 React 포트. 같은 계산을 useEffect 안에서 돌린다.
import { useEffect, useRef } from "react";
import styles from "./SendLabelLetterScatter.module.scss";
const cx = (s: string): string => s.split(" ").map((n) => styles[n] ?? n).join(" ");
export default function SendLabelLetterScatter() {
const rootRef = useRef<HTMLDivElement | null>(null);
useEffect(() => {
const rootEl = rootRef.current;
if (!rootEl) return;
const root: HTMLElement = rootEl;
type RGB = [number, number, number];
const W = 480;
const H = 300;
const FIXED_DT = 16;
// 파스텔 팔레트 — 캔버스와 스크립트가 칠하는 색은 여기서만 고른다 (scss 쪽 색은 demo-tokens)
const INK: RGB = [38, 33, 52];
const PAPER: RGB = [255, 252, 246];
const CREAM: RGB = [255, 243, 224];
const SKY: RGB = [158, 208, 255];
const LILAC: RGB = [200, 184, 255];
const MINT: RGB = [156, 228, 204];
const PINK: RGB = [255, 182, 204];
const PEACH: RGB = [255, 214, 184];
function clamp(v: number, lo: number, hi: number): number { return v < lo ? lo : (v > hi ? hi : v); }
function lerp(a: number, b: number, t: number): number { return a + (b - a) * t; }
function easeOut(x: number): number { const c = clamp(x, 0, 1); return 1 - Math.pow(1 - c, 3); }
function easeInOut(x: number): number {
const c = clamp(x, 0, 1);
return c < 0.5 ? 4 * c * c * c : 1 - Math.pow(-2 * c + 2, 3) / 2;
}
function rgba(c: RGB, a: number): string {
return 'rgba(' + Math.round(c[0]) + ',' + Math.round(c[1]) + ',' + Math.round(c[2]) + ',' + clamp(a, 0, 1).toFixed(3) + ')';
}
function mix(a: RGB, b: RGB, t: number): RGB { return [lerp(a[0], b[0], t), lerp(a[1], b[1], t), lerp(a[2], b[2], t)]; }
// 시드 고정 난수 — 같은 시드면 같은 값이 다시 나온다 (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;
};
}
const sceneEl = root.querySelector('[data-role="scene"]') as HTMLElement | null;
const statusEl = root.querySelector('[data-role="status"]') as HTMLElement | null;
if (!sceneEl || !statusEl) { return; }
const scene: HTMLElement = sceneEl;
const status: HTMLElement = statusEl;
const reduceQuery = window.matchMedia('(prefers-reduced-motion: reduce)');
const still = reduceQuery.matches;
const resizeHooks: Array<() => void> = [];
// 자동 시연 중인가 — 사람이 처음 만지는 순간 시연을 멈추고 처음 상태로 돌린 뒤 상태 줄을 읽어 주기 시작한다
let demo = root.classList.contains('is-demo');
function wake(): void {
if (!demo) { return; }
demo = false;
root.classList.remove('is-demo');
status.setAttribute('aria-live', 'polite');
resetIdle();
}
function say(text: string): void {
if (status.textContent !== text) { status.textContent = text; }
}
// 장면 배율 — 480×300 좌표로 짠 판을 상자 폭에 맞춰 통째로 줄인다
let k = 1;
function fitScene(): void {
const w = root.clientWidth;
k = w > 0 ? w / W : 1;
scene.style.transform = 'scale(' + k.toFixed(4) + ')';
}
// 화면 좌표(CSS px) → 장면 좌표(480×300). 줄인 배율 k 로 나눠야 판 안의 위치가 된다
function toScene(clientX: number, clientY: number): [number, number] {
const r = root.getBoundingClientRect();
return [(clientX - r.left) / k, (clientY - r.top) / k];
}
// 캡처 단계에서 듣는다 — 버튼 자신의 pointerdown 보다 먼저 시연을 끝내야 사람의 첫 누름이 처음 상태에서 시작한다
root.addEventListener('pointerdown', wake, true);
root.addEventListener('keydown', wake, true);
// 2D 값 노이즈 — 격자점마다 시드 난수 값을 두고 사이를 부드럽게 보간한다. 결과는 -1~1
function makeNoise(seed: number): (x: number, y: number) => number {
const rng = makeRng(seed);
const perm = new Uint8Array(512);
const vals = new Float32Array(256);
for (let i = 0; i < 256; i += 1) { vals[i] = rng() * 2 - 1; perm[i] = i; }
for (let i = 255; i > 0; i -= 1) {
const j = Math.floor(rng() * (i + 1));
const t = perm[i];
perm[i] = perm[j];
perm[j] = t;
}
for (let i = 0; i < 256; i += 1) { perm[i + 256] = perm[i]; }
function at(xi: number, yi: number): number { return vals[perm[(xi & 255) + perm[yi & 255]]]; }
return function (x: number, y: number): number {
const xi = Math.floor(x);
const yi = Math.floor(y);
const fx = x - xi;
const fy = y - yi;
const u = fx * fx * (3 - 2 * fx);
const v = fy * fy * (3 - 2 * fy);
const a = lerp(at(xi, yi), at(xi + 1, yi), u);
const b = lerp(at(xi, yi + 1), at(xi + 1, yi + 1), u);
return lerp(a, b, v);
};
}
type Glyph = { el: HTMLElement; ox: number; oy: number; rot: number };
type Phase = 'idle' | 'swap' | 'done';
const BTN_H = 52;
// 알약 가운데 몸통의 기준 너비(px) — scaleX 로 늘이고 양끝 반원은 따로 옮긴다
const MID_BASE = 100;
const PAD_X = 28;
// 글자 사이 출발 시차
const LETTER_STAGGER_MS = 34;
// 흩어지는 거리(px) — 글자마다 노이즈로 0.55~1 배
const SCATTER_AMP = 46;
// 새 글자가 스프링으로 제자리에 드는 시간 — 흔들림 폭이 처음의 3% 밑으로 줄어드는 시각
const REGATHER_MS = 520;
const REGATHER_ZETA = 0.42;
const REGATHER_DELAY = 140;
const SCATTER_MS = 360;
const DEMO_CYCLE = 2000;
const TXT_IDLE = '댓글 보내기';
const TXT_SENT = '보냈어요';
const TXT_READY = '댓글을 보낼 준비 됨';
const TXT_SWAP = '글자를 흩었다가 다시 모으는 중';
const TXT_DONE = '보냄 — 댓글이 올라갔어요';
const TXT_BACK = '새 댓글을 쓸 준비 됨';
const sendEl = root.querySelector('[data-role="send"]') as HTMLButtonElement | null;
const lettersEl = root.querySelector('[data-role="letters"]') as HTMLElement | null;
const capLEl = root.querySelector('[data-role="capl"]') as HTMLElement | null;
const capREl = root.querySelector('[data-role="capr"]') as HTMLElement | null;
const midEl = root.querySelector('[data-role="mid"]') as HTMLElement | null;
if (!sendEl || !lettersEl || !capLEl || !capREl || !midEl) { return; }
const send: HTMLButtonElement = sendEl;
const letters: HTMLElement = lettersEl;
const capL: HTMLElement = capLEl;
const capR: HTMLElement = capREl;
const mid: HTMLElement = midEl;
const noise = makeNoise(466);
// 스프링 감쇠 곡선의 두 값 — REGATHER_MS 에 폭이 3% 가 되게 감쇠율을 정하고, 감쇠비로 진동수를 낸다
const decayRate = Math.log(1 / 0.03) / REGATHER_MS;
const omegaD = (decayRate / REGATHER_ZETA) * Math.sqrt(1 - REGATHER_ZETA * REGATHER_ZETA);
let phase: Phase = 'idle';
let pt = 0;
let sent = false;
let oldGlyphs: Glyph[] = [];
let newGlyphs: Glyph[] = [];
let w0 = 0;
let w1 = 0;
let demoNext = 200;
// 남은 변위 비율 — 1 에서 시작해 진동하며 0 으로. 감쇠 사인(코사인) 하나로 스프링 해를 그린다
function springLeft(t: number): number {
if (t <= 0) { return 1; }
return Math.exp(-decayRate * t) * Math.cos(omegaD * t);
}
// 글자 i 의 흩어질 방향·거리·회전 — 같은 시드면 같은 글자는 같은 쪽으로 난다
function scatterOf(i: number, row: number): [number, number, number] {
const a = -Math.PI / 2 + noise(i * 0.61, row) * Math.PI * 0.9;
const d = SCATTER_AMP * (0.55 + 0.45 * (noise(i * 0.61, row + 7.3) * 0.5 + 0.5));
return [Math.cos(a) * d, Math.sin(a) * d, noise(i * 0.61, row + 13.1) * 40];
}
function makeLayer(text: string, row: number): Glyph[] {
const out: Glyph[] = [];
Array.from(text).forEach(function (ch: string, i: number): void {
const s = document.createElement('span');
s.className = letters.getAttribute('data-glyph') || '';
s.textContent = ch === ' ' ? ' ' : ch;
letters.appendChild(s);
const v = scatterOf(i, row);
out.push({ el: s, ox: v[0], oy: v[1], rot: v[2] });
});
return out;
}
function layerWidth(gs: Glyph[]): number {
let w = 0;
for (const g of gs) { w += g.el.getBoundingClientRect().width / k; }
return w > 0 ? w : gs.length * 14;
}
// 알약 너비 w — 양끝 반원은 ±(w/2 − 높이/2) 로 옮기고 가운데만 scaleX 로 늘인다(모서리가 늘어나 찌그러지지 않는다)
function setPill(w: number): void {
const half = Math.max(0, w / 2 - BTN_H / 2);
capL.style.transform = 'translateX(' + (-half).toFixed(2) + 'px)';
capR.style.transform = 'translateX(' + half.toFixed(2) + 'px)';
mid.style.transform = 'scaleX(' + ((half * 2) / MID_BASE).toFixed(4) + ')';
}
function clearLetters(): void {
while (letters.firstChild) { letters.removeChild(letters.firstChild); }
}
function showLabel(text: string): void {
clearLetters();
oldGlyphs = makeLayer(text, 0.5);
w0 = layerWidth(oldGlyphs) + PAD_X * 2;
setPill(w0);
send.setAttribute('aria-label', text);
}
// 버튼 판 너비 — 두 문구 중 긴 쪽 알약에 맞춰 한 번 정한다(포커스 테두리가 알약을 감싸게). 가운데 x 240 은 그대로
function fitButton(): void {
const probe = makeLayer(TXT_SENT, 9.9);
const w = Math.ceil(Math.max(layerWidth(probe) + PAD_X * 2, w0));
for (const g of probe) { letters.removeChild(g.el); }
send.style.width = w + 'px';
send.style.left = (W / 2 - w / 2).toFixed(1) + 'px';
}
function resetIdle(): void {
phase = 'idle';
pt = 0;
sent = false;
newGlyphs = [];
showLabel(TXT_IDLE);
fitButton();
say(TXT_READY);
}
function finish(): void {
phase = 'done';
pt = 0;
showLabel(sent ? TXT_SENT : TXT_IDLE);
say(sent ? TXT_DONE : TXT_BACK);
}
function settle(): void {
sent = true;
finish();
}
function press(): void {
if (phase === 'swap') { return; }
sent = !sent;
if (still) { finish(); return; }
const next = sent ? TXT_SENT : TXT_IDLE;
for (const g of oldGlyphs) { g.el.setAttribute('aria-hidden', 'true'); }
newGlyphs = makeLayer(next, 3.7);
w1 = layerWidth(newGlyphs) + PAD_X * 2;
send.setAttribute('aria-label', next);
phase = 'swap';
pt = 0;
say(TXT_SWAP);
}
function swapEnd(): number {
return REGATHER_DELAY + newGlyphs.length * LETTER_STAGGER_MS + REGATHER_MS;
}
function step(): void {
if (phase !== 'swap') { return; }
pt += FIXED_DT;
if (pt >= swapEnd()) { finish(); }
}
function demoTick(t: number): void {
if (t < demoNext) { return; }
demoNext += DEMO_CYCLE;
if (phase === 'swap') { finish(); }
press();
}
function draw(): void {
if (phase !== 'swap') { return; }
oldGlyphs.forEach(function (g: Glyph, i: number): void {
const p = clamp((pt - i * LETTER_STAGGER_MS) / SCATTER_MS, 0, 1);
const e = easeOut(p);
g.el.style.transform = 'translate(' + (g.ox * e).toFixed(2) + 'px,' + (g.oy * e + 18 * p * p).toFixed(2) + 'px) rotate(' + (g.rot * e).toFixed(1) + 'deg)';
g.el.style.opacity = (1 - p).toFixed(3);
});
newGlyphs.forEach(function (g: Glyph, j: number): void {
const tau = pt - REGATHER_DELAY - j * LETTER_STAGGER_MS;
const f = springLeft(tau);
// 새 글자는 흩어질 방향의 반대편에서 들어온다
g.el.style.transform = 'translate(' + (-g.ox * f).toFixed(2) + 'px,' + (-g.oy * f).toFixed(2) + 'px) rotate(' + (-g.rot * f).toFixed(1) + 'deg)';
g.el.style.opacity = clamp(tau / 120, 0, 1).toFixed(3);
});
// 너비도 같은 스프링 곡선으로 — 새 너비를 살짝 지나쳤다가 돌아온다
setPill(w1 + (w0 - w1) * springLeft(pt - REGATHER_DELAY));
}
send.addEventListener('click', function (): void { press(); });
resetIdle();
let rafId = 0;
let lastTs = -1;
let acc = 0;
let clock = 0;
function onResize(): void {
fitScene();
for (const f of resizeHooks) { f(); }
draw();
}
fitScene();
window.addEventListener('resize', onResize);
function frame(ts: number): void {
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;
if (demo) { demoTick(clock); }
step();
acc -= FIXED_DT;
n += 1;
}
draw();
rafId = window.requestAnimationFrame(frame);
}
if (still) {
settle();
draw();
} else {
rafId = window.requestAnimationFrame(frame);
}
return function (): void {
window.cancelAnimationFrame(rafId);
window.removeEventListener('resize', onResize);
};
}, []);
return (
<div className={cx("sb") + " is-demo"} ref={rootRef}>
<div className={cx("sb__scene")} data-role="scene">
<span className={cx("lt__box")} aria-hidden="true"><span className={cx("lt__line")}></span><span className={cx("lt__line lt__line--short")}></span></span>
<button className={cx("lt__send")} data-role="send" type="button">
<span className={cx("lt__pill")} aria-hidden="true">
<span className={cx("lt__mid")} data-role="mid"></span>
<span className={cx("lt__cap")} data-role="capl"></span>
<span className={cx("lt__cap")} data-role="capr"></span>
</span>
<span className={cx("lt__letters")} data-role="letters" data-glyph={cx("lt__glyph")}></span>
</button>
<p className={cx("sb__status")} data-role="status" aria-live="off">댓글을 보낼 준비 됨</p>
</div>
</div>
);
}07 A Button Label Whose Letters Scatter One by One and Regather as Sent — Measured area 4.192% · moving frames 13/23Original by GODRICH · SCSS and React ship in the zip · Send Button Animation CSS: 9 Fold-and-Fly Buttons
The post this demo lives in
Send Button Animation CSS: 9 Fold-and-Fly ButtonsA send button should show that something left — 01 folds into a paper plane that banks along a curve, 02 springs back as See all demos in this post
If you like this effect - similar demos
Buttons03 One button holding on and off9 button state css patterns, loading to done
Buttons01 Long-shadow retro — a button whose trailing shadow length value extends and retracts with hover stateCTA Button Design: 9 Interaction Patterns
Buttons09 Disabled ripple block — pressing a button whose disabled value is on stops the ripple-spread value midway and answers with a shake value insteadButton Group CSS: 9 Adjoined Patterns