08空と窓を映し、縁に近いほど反射が濃くなる玉
画素ごとに球面の法線から反射の向きを求め、空のグラデーションと窓の四角形から色を読み、視線と法線が斜めになるほど反射率が上がる近似式で混ぜる。奥の膜の内側の反射ももう一度足すので逆さの二つ目の窓が映り、中心は透明で、縁は空色の輪になる。
使いどころガラス質のアイコン・プレミアムカードのつや
EDGE_F0SKY_TILTWINDOW_GLINT

<main class="stage">
<div class="hs is-demo" id="hs">
<canvas class="hs__canvas" data-role="canvas" width="480" height="300" tabindex="0" aria-label="画素ごとに反射の向きで空のグラデーションと窓の四角形を読み、縁に近いほど反射が濃くなるシャボン玉。ドラッグすると空が回ります"></canvas>
<p class="hs__status" data-role="status" aria-live="off">空と窓が玉のまわりを回っています</p>
<div class="hs__tools">
<button class="hs__btn" data-role="turn" type="button" aria-pressed="false">回転を止める</button>
<button class="hs__btn" data-role="reset" type="button">最初の角度</button>
</div>
</div>
</main>@use "../../../../site/static/demo-tokens" as *;
@include stage($stage-ink);
.hs {
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;
}
.hs__canvas {
display: block;
width: 100%;
height: 100%;
cursor: crosshair;
}
.hs__canvas:focus-visible {
outline: 2px solid rgba(255, 255, 255, .85);
outline-offset: -6px;
}
.hs__status {
position: absolute;
left: $sp-3;
bottom: $sp-3;
box-sizing: border-box;
max-width: 34%;
margin: 0;
padding: $sp-1 $sp-3;
border-radius: $r-control;
background: rgba(255, 255, 255, .85);
color: $subject-ink;
font-weight: 500;
font-size: 11px;
line-height: 1.4;
pointer-events: none;
}
// 판은 오른쪽에 있다 — 버튼은 왼쪽 위 칸에 두고, 좁으면 줄을 바꿔 판을 덮지 않는다
.hs__tools {
position: absolute;
left: $sp-3;
top: $sp-3;
box-sizing: border-box;
max-width: 34%;
display: flex;
flex-wrap: wrap;
gap: $sp-2;
}
.hs__btn {
margin: 0;
padding: $sp-1 $sp-3;
border: 0;
border-radius: $r-pill;
background: rgba(255, 255, 255, .85);
color: $subject-ink;
font: inherit;
font-weight: 500;
font-size: 12px;
line-height: 1.4;
cursor: pointer;
transition: background-color $dur-quick ease-out;
}
.hs__btn:hover {
background: $subject-cream;
}
.hs__btn[aria-pressed="true"] {
background: $subject-mint;
}
.hs__btn:focus-visible {
outline: 2px solid rgba(255, 255, 255, .95);
outline-offset: 2px;
}
// 손가락 가로 끌기는 이 캔버스가 받고, 세로 쓸기는 브라우저에 남겨 페이지 스크롤이 막히지 않게 한다
.hs__canvas { touch-action: pan-y; }
@media (max-width: 340px) {
.hs__btn { font-size: 10px; padding: $sp-1 $sp-2; }
.hs__status { font-size: 10px; padding: $sp-1 $sp-2; }
}
@media (prefers-reduced-motion: reduce) {
.hs__btn { transition: none; }
}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);
}
.hs {
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;
}
.hs__canvas {
display: block;
width: 100%;
height: 100%;
cursor: crosshair;
}
.hs__canvas:focus-visible {
outline: 2px solid rgba(255, 255, 255, 0.85);
outline-offset: -6px;
}
.hs__status {
position: absolute;
left: 12px;
bottom: 12px;
box-sizing: border-box;
max-width: 34%;
margin: 0;
padding: 4px 12px;
border-radius: 12px;
background: rgba(255, 255, 255, 0.85);
color: #17141a;
font-weight: 500;
font-size: 11px;
line-height: 1.4;
pointer-events: none;
}
.hs__tools {
position: absolute;
left: 12px;
top: 12px;
box-sizing: border-box;
max-width: 34%;
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.hs__btn {
margin: 0;
padding: 4px 12px;
border: 0;
border-radius: 999px;
background: rgba(255, 255, 255, 0.85);
color: #17141a;
font: inherit;
font-weight: 500;
font-size: 12px;
line-height: 1.4;
cursor: pointer;
transition: background-color 220ms ease-out;
}
.hs__btn:hover {
background: #fff7e6;
}
.hs__btn[aria-pressed=true] {
background: #4cd4a6;
}
.hs__btn:focus-visible {
outline: 2px solid rgba(255, 255, 255, 0.95);
outline-offset: 2px;
}
.hs__canvas {
touch-action: pan-y;
}
@media (max-width: 340px) {
.hs__btn {
font-size: 10px;
padding: 4px 8px;
}
.hs__status {
font-size: 10px;
padding: 4px 8px;
}
}
@media (prefers-reduced-motion: reduce) {
.hs__btn {
transition: none;
}
}(function () {
const root = document.getElementById("hs");
if (!root) return;
const W = 480;
const H = 300;
const FIXED_DT = 16;
// 파스텔 팔레트 — 어두운 무대 위에 밝은 막을 얹어 명도 차로 방울이 읽힌다 (막의 무지갯빛은 이 표가 아니라 두께 계산에서 나온다)
const BG = [29, 26, 44];
const DEEP = [44, 39, 64];
const PAPER = [255, 248, 234];
const INK = [58, 48, 76];
const MINT = [126, 226, 192];
const SKY = [124, 196, 255];
const LILAC = [190, 164, 255];
const PINK = [255, 160, 190];
const PEACH = [255, 208, 168];
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(c[0]) + ',' + Math.round(c[1]) + ',' + Math.round(c[2]) + ',' + clamp(a, 0, 1).toFixed(3) + ')';
}
function mix(a, b, k) { return [lerp(a[0], b[0], k), lerp(a[1], b[1], k), lerp(a[2], b[2], k)]; }
const canvasEl = root.querySelector('[data-role="canvas"]');
const statusEl = root.querySelector('[data-role="status"]');
const ctxRaw = canvasEl ? canvasEl.getContext('2d') : null;
if (!canvasEl || !ctxRaw || !statusEl) {
return;
}
const cv = canvasEl;
const ctx = ctxRaw;
const status = statusEl;
const reduceQuery = window.matchMedia('(prefers-reduced-motion: reduce)');
let still = reduceQuery.matches;
// 자동 시연 중인가 — 사람이 처음 만지는 순간 시연을 멈추고 상태 줄을 읽어 주기 시작한다
let demo = root.classList.contains('is-demo');
function wake() {
if (!demo) {
return;
}
demo = false;
root.classList.remove('is-demo');
status.setAttribute('aria-live', 'polite');
}
function say(text) {
if (status.textContent !== text) {
status.textContent = text;
}
}
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 onResize() {
fitCanvas();
draw();
}
fitCanvas();
window.addEventListener('resize', onResize);
// 화면 좌표(CSS px) → 장면 좌표(480x300). 리사이즈 뒤에도 늘 현재 크기로 다시 잰다
function toScene(ev) {
const r = cv.getBoundingClientRect();
return [((ev.clientX - r.left) / r.width) * W, ((ev.clientY - r.top) / r.height) * H];
}
// 시드 고정 난수 — 같은 시드면 같은 장면이 다시 나온다 (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;
};
}
// 왼쪽 칸의 수치 — 이름표 한 줄 + 값 한 줄
function panelRow(row, label, value) {
const y = 112 + row * 34;
ctx.textAlign = 'left';
ctx.textBaseline = 'alphabetic';
ctx.fillStyle = rgba(PAPER, 0.62);
ctx.font = '500 11px sans-serif';
ctx.fillText(label, 16, y);
ctx.fillStyle = rgba(PAPER, 0.96);
ctx.font = '700 15px sans-serif';
ctx.fillText(value, 16, y + 18);
}
function clearStage() {
ctx.fillStyle = rgba(BG, 1);
ctx.fillRect(0, 0, W, H);
}
function makePix(w, h) {
const c = document.createElement('canvas');
c.width = w;
c.height = h;
const pc = c.getContext('2d');
if (!pc) {
return null;
}
const img = pc.createImageData(w, h);
return { cvs: c, pc: pc, img: img, px: img.data, w: w, h: h };
}
// putImageData 는 캔버스 변환(배율)을 무시한다 — 작은 캔버스에 올린 뒤 drawImage 로 장면 좌표에 그린다
function showPix(p, x, y) {
p.pc.putImageData(p.img, 0, 0);
ctx.drawImage(p.cvs, x, y, p.w, p.h);
}
// 08 — 화소마다 구면 법선으로 반사 방향을 구해 하늘 그라디언트와 창문 사각형에서 색을 읽고, 비스듬할수록 커지는 반사율로 섞는다
// 정면(시선과 법선이 나란할 때)의 반사율 — 막은 비쳐 보이는 게 대부분이다
const EDGE_F0 = 0.04;
// 하늘을 앞뒤로 기울이는 각(rad) — 반사 방향을 x 축으로 이만큼 돌려 읽는다
const SKY_TILT = 0.18;
// 창문 밝기 배율 — 하늘보다 훨씬 밝은 빛이라 반사율이 낮은 가운데서도 비친다
const WINDOW_GLINT = 7;
// 하늘 밝기 배율 — 화면 색보다 밝은 빛으로 두어 반사율이 낮은 자리에서도 하늘빛이 얹힌다
const SKY_GAIN = 1.5;
// 하늘이 방울 둘레를 도는 빠르기(rad/s)
const TURN_SPEED = 0.55;
// 창문 — 가운데 방위각에서 좌우 반폭(rad), 아래·위 고도(rad), 창살 굵기(rad)
const WIN_AZ = 0;
const WIN_HALF = 0.4;
const WIN_EL0 = 0.1;
const WIN_EL1 = 0.7;
const WIN_BAR = 0.022;
const BCX = 318;
const BCY = 150;
const BR = 120;
const BOB = 6;
const HORIZON = [255, 214, 184];
const ZENITH = [120, 186, 255];
const GROUND_NEAR = [118, 170, 140];
const GROUND_FAR = [52, 64, 66];
const TXT_TURN = '空と窓が玉のまわりを回っています';
const TXT_HOLD = '回転を止める';
const TXT_DRAG = '空の向きを動かしました';
const turnBtn = root.querySelector('[data-role="turn"]');
const resetBtn = root.querySelector('[data-role="reset"]');
const back = makePix(W, H);
const BOX = BR * 2 + 2;
const pix = makePix(BOX, BOX + BOB * 2);
let yaw = -0.9;
let tilt = SKY_TILT;
let turning = true;
let tSec = 0;
let bob = 0;
let dragX = -1;
let dragY = -1;
let lastText = TXT_TURN;
// 비스듬할수록 반사율이 커지는 근사식 — F = F0 + (1 − F0)(1 − cosθ)⁵
function reflectance(cosView) {
const m = 1 - cosView;
return EDGE_F0 + (1 - EDGE_F0) * m * m * m * m * m;
}
// 방울 뒤 무대 — 한 번 화소로 구워 두고, 방울 화소는 같은 자리 값을 읽어 비쳐 보이게 한다
function backAt(x, y) {
let c = mix(BG, DEEP, smooth(y / 230));
if (y > 232) {
c = mix(DEEP, INK, smooth((y - 232) / 40));
}
const g1 = Math.exp(-((x - 120) * (x - 120) + (y - 80) * (y - 80)) / (2 * 90 * 90));
const g2 = Math.exp(-((x - 430) * (x - 430) + (y - 250) * (y - 250)) / (2 * 80 * 80));
c = mix(c, LILAC, g1 * 0.2);
return mix(c, MINT, g2 * 0.14);
}
function bakeBack() {
if (!back) {
return;
}
const px = back.px;
for (let y = 0; y < H; y += 1) {
for (let x = 0; x < W; x += 1) {
const c = backAt(x + 0.5, y + 0.5);
const o = (y * W + x) * 4;
px[o] = c[0];
px[o + 1] = c[1];
px[o + 2] = c[2];
px[o + 3] = 255;
}
}
back.pc.putImageData(back.img, 0, 0);
}
function wrapPi(a) {
let v = a % (Math.PI * 2);
if (v > Math.PI) {
v -= Math.PI * 2;
}
if (v < -Math.PI) {
v += Math.PI * 2;
}
return v;
}
const env = [0, 0, 0];
// 반사 방향(rx, ry, rz — 화면 아래가 +y, 보는 사람 쪽이 +z)에서 주변 색을 읽는다
function sampleEnv(rx, ry, rz) {
const cy = ry * Math.cos(tilt) - rz * Math.sin(tilt);
const cz = ry * Math.sin(tilt) + rz * Math.cos(tilt);
const el = Math.asin(clamp(-cy, -1, 1));
const az = Math.atan2(rx, cz) + yaw;
let c;
if (el < 0) {
c = mix(GROUND_NEAR, GROUND_FAR, Math.min(-el * 2, 1));
}
else {
const sky = mix(HORIZON, ZENITH, smooth(el / 1.2));
c = [sky[0] * SKY_GAIN, sky[1] * SKY_GAIN, sky[2] * SKY_GAIN];
const da = wrapPi(az - WIN_AZ);
if (Math.abs(da) < WIN_HALF && el > WIN_EL0 && el < WIN_EL1) {
const bar = Math.abs(da) < WIN_BAR || Math.abs(el - (WIN_EL0 + WIN_EL1) / 2) < WIN_BAR;
c = bar ? [INK[0], INK[1], INK[2]] : [PAPER[0] * WINDOW_GLINT, PAPER[1] * WINDOW_GLINT, PAPER[2] * WINDOW_GLINT];
}
}
env[0] = c[0];
env[1] = c[1];
env[2] = c[2];
}
function paintBubble() {
if (!pix || !back) {
return;
}
const px = pix.px;
const bg = back.px;
const top = BCY - BR - 1 - BOB;
const left = BCX - BR - 1;
const cy0 = BCY + bob;
for (let j = 0; j < pix.h; j += 1) {
const y = top + j + 0.5;
const ny = (y - cy0) / BR;
for (let i = 0; i < BOX; i += 1) {
const x = left + i + 0.5;
const nx = (x - BCX) / BR;
const r2 = nx * nx + ny * ny;
const o = (j * BOX + i) * 4;
if (r2 >= 1) {
px[o + 3] = 0;
continue;
}
const z = Math.sqrt(1 - r2);
// 들어온 시선 (0,0,−1) 을 법선에 비춰 돌린 방향 = 2z·n − (0,0,1)
sampleEnv(2 * z * nx, 2 * z * ny, 2 * z * z - 1);
const f0 = env[0];
const f1 = env[1];
const f2 = env[2];
// 뒤쪽 막 안쪽 면에서 한 번 더 — 법선이 안을 향해 반사 방향의 x·y 가 뒤집힌다(거꾸로 선 두 번째 창문)
sampleEnv(-2 * z * nx, -2 * z * ny, 2 * z * z - 1);
const f = reflectance(z);
const t = (1 - f) * (1 - f);
const bo = (clamp(Math.floor(y), 0, H - 1) * W + clamp(Math.floor(x), 0, W - 1)) * 4;
px[o] = bg[bo] * t + f0 * f + env[0] * f * (1 - f);
px[o + 1] = bg[bo + 1] * t + f1 * f + env[1] * f * (1 - f);
px[o + 2] = bg[bo + 2] * t + f2 * f + env[2] * f * (1 - f);
px[o + 3] = 255 * clamp((1 - Math.sqrt(r2)) * BR, 0, 1);
}
}
showPix(pix, left, top);
}
function step() {
const dt = FIXED_DT / 1000;
if (!turning) {
return;
}
tSec += dt;
yaw += TURN_SPEED * dt;
bob = Math.sin(tSec * 2.4) * BOB;
}
function settle() {
say(lastText);
}
function demoTick(t) {
if (t < 0) {
yaw = 0;
}
}
function draw() {
if (back) {
ctx.drawImage(back.cvs, 0, 0, W, H);
}
else {
clearStage();
}
ctx.fillStyle = rgba(BG, 0.55);
ctx.beginPath();
ctx.ellipse(BCX, BCY + BR + 16, BR * 0.6, 7, 0, 0, Math.PI * 2);
ctx.fill();
paintBubble();
panelRow(0, '中心の反射率', (reflectance(1) * 100).toFixed(1) + ' %');
panelRow(1, '縁の反射率', (reflectance(Math.sqrt(1 - 0.97 * 0.97)) * 100).toFixed(1) + ' %');
panelRow(2, '空の傾き', (tilt * 180 / Math.PI).toFixed(0) + '°');
}
function after(text) {
lastText = text;
say(text);
draw();
}
function setTurning(v) {
turning = v;
if (turnBtn) {
turnBtn.setAttribute('aria-pressed', v ? 'false' : 'true');
}
after(v ? TXT_TURN : TXT_HOLD);
}
function nudge(dYaw, dTilt) {
yaw += dYaw;
tilt = clamp(tilt + dTilt, -0.6, 0.6);
after(TXT_DRAG);
}
cv.addEventListener('pointerdown', function (ev) {
ev.preventDefault();
wake();
cv.setPointerCapture(ev.pointerId);
const p = toScene(ev);
dragX = p[0];
dragY = p[1];
after(TXT_DRAG);
});
cv.addEventListener('pointermove', function (ev) {
if (dragX < 0) {
return;
}
const p = toScene(ev);
nudge((p[0] - dragX) * 0.012, (p[1] - dragY) * 0.004);
dragX = p[0];
dragY = p[1];
});
function endDrag() { dragX = -1; dragY = -1; }
cv.addEventListener('pointerup', endDrag);
cv.addEventListener('pointercancel', endDrag);
cv.addEventListener('keydown', function (ev) {
const k = ev.key;
if (k === 'ArrowLeft') {
ev.preventDefault();
wake();
nudge(-0.15, 0);
}
else if (k === 'ArrowRight') {
ev.preventDefault();
wake();
nudge(0.15, 0);
}
else if (k === 'ArrowUp') {
ev.preventDefault();
wake();
nudge(0, -0.05);
}
else if (k === 'ArrowDown') {
ev.preventDefault();
wake();
nudge(0, 0.05);
}
else if (k === ' ' || k === 'Spacebar' || k === 'Enter') {
ev.preventDefault();
wake();
setTurning(!turning);
}
else if (k === 'Home') {
ev.preventDefault();
wake();
yaw = -0.9;
tilt = SKY_TILT;
after(TXT_TURN);
}
});
if (turnBtn) {
turnBtn.addEventListener('click', function () { wake(); setTurning(!turning); });
}
if (resetBtn) {
resetBtn.addEventListener('click', function () { wake(); yaw = -0.9; tilt = SKY_TILT; after(TXT_TURN); });
}
bakeBack();
say(TXT_TURN);
let rafId = 0;
let lastTs = -1;
let acc = 0;
let clock = 0;
let looping = false;
function frame(ts) {
if (!looping) {
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;
if (demo) {
demoTick(clock);
}
step();
acc -= FIXED_DT;
n += 1;
}
draw();
rafId = window.requestAnimationFrame(frame);
}
function startLoop() {
if (looping) {
return;
}
looping = true;
lastTs = -1;
acc = 0;
rafId = window.requestAnimationFrame(frame);
}
function stopLoop() {
looping = false;
window.cancelAnimationFrame(rafId);
}
// 움직임 줄이기 설정을 페이지를 연 채로 바꿔도 바로 따른다 — 켜면 루프를 멈추고 끝난 장면 한 장, 끄면 다시 돈다
function applyMotion() {
still = reduceQuery.matches;
if (still) {
stopLoop();
settle();
draw();
}
else {
startLoop();
}
}
reduceQuery.addEventListener('change', applyMotion);
applyMotion();
return function () {
stopLoop();
reduceQuery.removeEventListener('change', applyMotion);
window.removeEventListener('resize', onResize);
};
})();// SbSkyReflectionEdgeGlare - vanilla 판(08-sb-sky-reflection-edge-glare) 의 React 포트. 같은 계산을 useEffect 안에서 돌린다.
import { useEffect, useRef } from "react";
import styles from "./SbSkyReflectionEdgeGlare.module.scss";
const cx = (s: string): string => s.split(" ").map((n) => styles[n] ?? n).join(" ");
export default function SbSkyReflectionEdgeGlare() {
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;
// 파스텔 팔레트 — 어두운 무대 위에 밝은 막을 얹어 명도 차로 방울이 읽힌다 (막의 무지갯빛은 이 표가 아니라 두께 계산에서 나온다)
const BG: RGB = [29, 26, 44];
const DEEP: RGB = [44, 39, 64];
const PAPER: RGB = [255, 248, 234];
const INK: RGB = [58, 48, 76];
const MINT: RGB = [126, 226, 192];
const SKY: RGB = [124, 196, 255];
const LILAC: RGB = [190, 164, 255];
const PINK: RGB = [255, 160, 190];
const PEACH: RGB = [255, 208, 168];
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(c[0]) + ',' + Math.round(c[1]) + ',' + Math.round(c[2]) + ',' + clamp(a, 0, 1).toFixed(3) + ')';
}
function mix(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)]; }
const canvasEl = root.querySelector('[data-role="canvas"]') as HTMLCanvasElement | null;
const statusEl = root.querySelector('[data-role="status"]') as HTMLElement | null;
const ctxRaw = canvasEl ? canvasEl.getContext('2d') : null;
if (!canvasEl || !ctxRaw || !statusEl) { return; }
const cv: HTMLCanvasElement = canvasEl;
const ctx: CanvasRenderingContext2D = ctxRaw;
const status: HTMLElement = statusEl;
const reduceQuery = window.matchMedia('(prefers-reduced-motion: reduce)');
let still = reduceQuery.matches;
// 자동 시연 중인가 — 사람이 처음 만지는 순간 시연을 멈추고 상태 줄을 읽어 주기 시작한다
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');
}
function say(text: string): void {
if (status.textContent !== text) { status.textContent = text; }
}
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 onResize(): void {
fitCanvas();
draw();
}
fitCanvas();
window.addEventListener('resize', onResize);
// 화면 좌표(CSS px) → 장면 좌표(480x300). 리사이즈 뒤에도 늘 현재 크기로 다시 잰다
function toScene(ev: PointerEvent): [number, number] {
const r = cv.getBoundingClientRect();
return [((ev.clientX - r.left) / r.width) * W, ((ev.clientY - r.top) / r.height) * H];
}
// 시드 고정 난수 — 같은 시드면 같은 장면이 다시 나온다 (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;
};
}
// 왼쪽 칸의 수치 — 이름표 한 줄 + 값 한 줄
function panelRow(row: number, label: string, value: string): void {
const y = 112 + row * 34;
ctx.textAlign = 'left';
ctx.textBaseline = 'alphabetic';
ctx.fillStyle = rgba(PAPER, 0.62);
ctx.font = '500 11px sans-serif';
ctx.fillText(label, 16, y);
ctx.fillStyle = rgba(PAPER, 0.96);
ctx.font = '700 15px sans-serif';
ctx.fillText(value, 16, y + 18);
}
function clearStage(): void {
ctx.fillStyle = rgba(BG, 1);
ctx.fillRect(0, 0, W, H);
}
// 화소 계산판 — 작은 캔버스 하나에 ImageData 를 붙여 두고 화소를 직접 채운다
type Pix = { cvs: HTMLCanvasElement; pc: CanvasRenderingContext2D; img: ImageData; px: Uint8ClampedArray; w: number; h: number };
function makePix(w: number, h: number): Pix | null {
const c = document.createElement('canvas');
c.width = w;
c.height = h;
const pc = c.getContext('2d');
if (!pc) { return null; }
const img = pc.createImageData(w, h);
return { cvs: c, pc: pc, img: img, px: img.data, w: w, h: h };
}
// putImageData 는 캔버스 변환(배율)을 무시한다 — 작은 캔버스에 올린 뒤 drawImage 로 장면 좌표에 그린다
function showPix(p: Pix, x: number, y: number): void {
p.pc.putImageData(p.img, 0, 0);
ctx.drawImage(p.cvs, x, y, p.w, p.h);
}
// 08 — 화소마다 구면 법선으로 반사 방향을 구해 하늘 그라디언트와 창문 사각형에서 색을 읽고, 비스듬할수록 커지는 반사율로 섞는다
// 정면(시선과 법선이 나란할 때)의 반사율 — 막은 비쳐 보이는 게 대부분이다
const EDGE_F0 = 0.04;
// 하늘을 앞뒤로 기울이는 각(rad) — 반사 방향을 x 축으로 이만큼 돌려 읽는다
const SKY_TILT = 0.18;
// 창문 밝기 배율 — 하늘보다 훨씬 밝은 빛이라 반사율이 낮은 가운데서도 비친다
const WINDOW_GLINT = 7;
// 하늘 밝기 배율 — 화면 색보다 밝은 빛으로 두어 반사율이 낮은 자리에서도 하늘빛이 얹힌다
const SKY_GAIN = 1.5;
// 하늘이 방울 둘레를 도는 빠르기(rad/s)
const TURN_SPEED = 0.55;
// 창문 — 가운데 방위각에서 좌우 반폭(rad), 아래·위 고도(rad), 창살 굵기(rad)
const WIN_AZ = 0;
const WIN_HALF = 0.4;
const WIN_EL0 = 0.1;
const WIN_EL1 = 0.7;
const WIN_BAR = 0.022;
const BCX = 318;
const BCY = 150;
const BR = 120;
const BOB = 6;
const HORIZON: RGB = [255, 214, 184];
const ZENITH: RGB = [120, 186, 255];
const GROUND_NEAR: RGB = [118, 170, 140];
const GROUND_FAR: RGB = [52, 64, 66];
const TXT_TURN = '하늘과 창문이 방울 둘레를 도는 중';
const TXT_HOLD = '돌리기 멈춤';
const TXT_DRAG = '하늘 방향을 옮김';
const turnBtn = root.querySelector('[data-role="turn"]') as HTMLButtonElement | null;
const resetBtn = root.querySelector('[data-role="reset"]') as HTMLButtonElement | null;
const back = makePix(W, H);
const BOX = BR * 2 + 2;
const pix = makePix(BOX, BOX + BOB * 2);
let yaw = -0.9;
let tilt = SKY_TILT;
let turning = true;
let tSec = 0;
let bob = 0;
let dragX = -1;
let dragY = -1;
let lastText = TXT_TURN;
// 비스듬할수록 반사율이 커지는 근사식 — F = F0 + (1 − F0)(1 − cosθ)⁵
function reflectance(cosView: number): number {
const m = 1 - cosView;
return EDGE_F0 + (1 - EDGE_F0) * m * m * m * m * m;
}
// 방울 뒤 무대 — 한 번 화소로 구워 두고, 방울 화소는 같은 자리 값을 읽어 비쳐 보이게 한다
function backAt(x: number, y: number): RGB {
let c: RGB = mix(BG, DEEP, smooth(y / 230));
if (y > 232) { c = mix(DEEP, INK, smooth((y - 232) / 40)); }
const g1 = Math.exp(-((x - 120) * (x - 120) + (y - 80) * (y - 80)) / (2 * 90 * 90));
const g2 = Math.exp(-((x - 430) * (x - 430) + (y - 250) * (y - 250)) / (2 * 80 * 80));
c = mix(c, LILAC, g1 * 0.2);
return mix(c, MINT, g2 * 0.14);
}
function bakeBack(): void {
if (!back) { return; }
const px = back.px;
for (let y = 0; y < H; y += 1) {
for (let x = 0; x < W; x += 1) {
const c = backAt(x + 0.5, y + 0.5);
const o = (y * W + x) * 4;
px[o] = c[0]; px[o + 1] = c[1]; px[o + 2] = c[2]; px[o + 3] = 255;
}
}
back.pc.putImageData(back.img, 0, 0);
}
function wrapPi(a: number): number {
let v = a % (Math.PI * 2);
if (v > Math.PI) { v -= Math.PI * 2; }
if (v < -Math.PI) { v += Math.PI * 2; }
return v;
}
const env: RGB = [0, 0, 0];
// 반사 방향(rx, ry, rz — 화면 아래가 +y, 보는 사람 쪽이 +z)에서 주변 색을 읽는다
function sampleEnv(rx: number, ry: number, rz: number): void {
const cy = ry * Math.cos(tilt) - rz * Math.sin(tilt);
const cz = ry * Math.sin(tilt) + rz * Math.cos(tilt);
const el = Math.asin(clamp(-cy, -1, 1));
const az = Math.atan2(rx, cz) + yaw;
let c: RGB;
if (el < 0) {
c = mix(GROUND_NEAR, GROUND_FAR, Math.min(-el * 2, 1));
} else {
const sky = mix(HORIZON, ZENITH, smooth(el / 1.2));
c = [sky[0] * SKY_GAIN, sky[1] * SKY_GAIN, sky[2] * SKY_GAIN];
const da = wrapPi(az - WIN_AZ);
if (Math.abs(da) < WIN_HALF && el > WIN_EL0 && el < WIN_EL1) {
const bar = Math.abs(da) < WIN_BAR || Math.abs(el - (WIN_EL0 + WIN_EL1) / 2) < WIN_BAR;
c = bar ? [INK[0], INK[1], INK[2]] : [PAPER[0] * WINDOW_GLINT, PAPER[1] * WINDOW_GLINT, PAPER[2] * WINDOW_GLINT];
}
}
env[0] = c[0]; env[1] = c[1]; env[2] = c[2];
}
function paintBubble(): void {
if (!pix || !back) { return; }
const px = pix.px;
const bg = back.px;
const top = BCY - BR - 1 - BOB;
const left = BCX - BR - 1;
const cy0 = BCY + bob;
for (let j = 0; j < pix.h; j += 1) {
const y = top + j + 0.5;
const ny = (y - cy0) / BR;
for (let i = 0; i < BOX; i += 1) {
const x = left + i + 0.5;
const nx = (x - BCX) / BR;
const r2 = nx * nx + ny * ny;
const o = (j * BOX + i) * 4;
if (r2 >= 1) { px[o + 3] = 0; continue; }
const z = Math.sqrt(1 - r2);
// 들어온 시선 (0,0,−1) 을 법선에 비춰 돌린 방향 = 2z·n − (0,0,1)
sampleEnv(2 * z * nx, 2 * z * ny, 2 * z * z - 1);
const f0 = env[0];
const f1 = env[1];
const f2 = env[2];
// 뒤쪽 막 안쪽 면에서 한 번 더 — 법선이 안을 향해 반사 방향의 x·y 가 뒤집힌다(거꾸로 선 두 번째 창문)
sampleEnv(-2 * z * nx, -2 * z * ny, 2 * z * z - 1);
const f = reflectance(z);
const t = (1 - f) * (1 - f);
const bo = (clamp(Math.floor(y), 0, H - 1) * W + clamp(Math.floor(x), 0, W - 1)) * 4;
px[o] = bg[bo] * t + f0 * f + env[0] * f * (1 - f);
px[o + 1] = bg[bo + 1] * t + f1 * f + env[1] * f * (1 - f);
px[o + 2] = bg[bo + 2] * t + f2 * f + env[2] * f * (1 - f);
px[o + 3] = 255 * clamp((1 - Math.sqrt(r2)) * BR, 0, 1);
}
}
showPix(pix, left, top);
}
function step(): void {
const dt = FIXED_DT / 1000;
if (!turning) { return; }
tSec += dt;
yaw += TURN_SPEED * dt;
bob = Math.sin(tSec * 2.4) * BOB;
}
function settle(): void {
say(lastText);
}
function demoTick(t: number): void {
if (t < 0) { yaw = 0; }
}
function draw(): void {
if (back) { ctx.drawImage(back.cvs, 0, 0, W, H); } else { clearStage(); }
ctx.fillStyle = rgba(BG, 0.55);
ctx.beginPath();
ctx.ellipse(BCX, BCY + BR + 16, BR * 0.6, 7, 0, 0, Math.PI * 2);
ctx.fill();
paintBubble();
panelRow(0, '가운데 반사율', (reflectance(1) * 100).toFixed(1) + ' %');
panelRow(1, '가장자리 반사율', (reflectance(Math.sqrt(1 - 0.97 * 0.97)) * 100).toFixed(1) + ' %');
panelRow(2, '하늘 기울기', (tilt * 180 / Math.PI).toFixed(0) + '°');
}
function after(text: string): void {
lastText = text;
say(text);
draw();
}
function setTurning(v: boolean): void {
turning = v;
if (turnBtn) { turnBtn.setAttribute('aria-pressed', v ? 'false' : 'true'); }
after(v ? TXT_TURN : TXT_HOLD);
}
function nudge(dYaw: number, dTilt: number): void {
yaw += dYaw;
tilt = clamp(tilt + dTilt, -0.6, 0.6);
after(TXT_DRAG);
}
cv.addEventListener('pointerdown', function (ev: PointerEvent): void {
ev.preventDefault();
wake();
cv.setPointerCapture(ev.pointerId);
const p = toScene(ev);
dragX = p[0];
dragY = p[1];
after(TXT_DRAG);
});
cv.addEventListener('pointermove', function (ev: PointerEvent): void {
if (dragX < 0) { return; }
const p = toScene(ev);
nudge((p[0] - dragX) * 0.012, (p[1] - dragY) * 0.004);
dragX = p[0];
dragY = p[1];
});
function endDrag(): void { dragX = -1; dragY = -1; }
cv.addEventListener('pointerup', endDrag);
cv.addEventListener('pointercancel', endDrag);
cv.addEventListener('keydown', function (ev: KeyboardEvent): void {
const k = ev.key;
if (k === 'ArrowLeft') { ev.preventDefault(); wake(); nudge(-0.15, 0); }
else if (k === 'ArrowRight') { ev.preventDefault(); wake(); nudge(0.15, 0); }
else if (k === 'ArrowUp') { ev.preventDefault(); wake(); nudge(0, -0.05); }
else if (k === 'ArrowDown') { ev.preventDefault(); wake(); nudge(0, 0.05); }
else if (k === ' ' || k === 'Spacebar' || k === 'Enter') { ev.preventDefault(); wake(); setTurning(!turning); }
else if (k === 'Home') { ev.preventDefault(); wake(); yaw = -0.9; tilt = SKY_TILT; after(TXT_TURN); }
});
if (turnBtn) { turnBtn.addEventListener('click', function (): void { wake(); setTurning(!turning); }); }
if (resetBtn) { resetBtn.addEventListener('click', function (): void { wake(); yaw = -0.9; tilt = SKY_TILT; after(TXT_TURN); }); }
bakeBack();
say(TXT_TURN);
let rafId = 0;
let lastTs = -1;
let acc = 0;
let clock = 0;
let looping = false;
function frame(ts: number): void {
if (!looping) { 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;
if (demo) { demoTick(clock); }
step();
acc -= FIXED_DT;
n += 1;
}
draw();
rafId = window.requestAnimationFrame(frame);
}
function startLoop(): void {
if (looping) { return; }
looping = true;
lastTs = -1;
acc = 0;
rafId = window.requestAnimationFrame(frame);
}
function stopLoop(): void {
looping = false;
window.cancelAnimationFrame(rafId);
}
// 움직임 줄이기 설정을 페이지를 연 채로 바꿔도 바로 따른다 — 켜면 루프를 멈추고 끝난 장면 한 장, 끄면 다시 돈다
function applyMotion(): void {
still = reduceQuery.matches;
if (still) {
stopLoop();
settle();
draw();
} else {
startLoop();
}
}
reduceQuery.addEventListener('change', applyMotion);
applyMotion();
return function (): void {
stopLoop();
reduceQuery.removeEventListener('change', applyMotion);
window.removeEventListener('resize', onResize);
};
}, []);
return (
<div className={cx("hs") + " is-demo"} ref={rootRef}>
<canvas className={cx("hs__canvas")} data-role="canvas" width={480} height={300} tabIndex={0} aria-label="화소마다 반사 방향으로 하늘 그라디언트와 창문 사각형을 읽어 가장자리로 갈수록 반사가 짙어지는 비눗방울. 끌면 하늘이 돈다"></canvas>
<p className={cx("hs__status")} data-role="status" aria-live="off">하늘과 창문이 방울 둘레를 도는 중</p>
<div className={cx("hs__tools")}>
<button className={cx("hs__btn")} data-role="turn" type="button" aria-pressed="false">돌리기 멈춤</button>
<button className={cx("hs__btn")} data-role="reset" type="button">처음 각도</button>
</div>
</div>
);
}08 空と窓を映し、縁に近いほど反射が濃くなる玉 — 計測 累積面積 11.57% · 動いたフレーム 23/23GODRICH オリジナル · SCSS と React は zip に同梱 · シャボン玉 アニメーション 9種 — 膜の虹色と割れる瞬間
このデモが属する記事
シャボン玉 アニメーション 9種 — 膜の虹色と割れる瞬間シャボン玉の虹色は塗った色ではなく、膜の厚さが生む光のずれです — 01番は厚さから色を計算し、04番は突いた所から縁がめくれて割れ、06番はくっついた二つの玉の間に曲がった膜ができます。ここに集めたシャボン玉 アニメーション9場面は、画像 この記事のデモをすべて見る

