04Specular highlight — sun glitter
Dotting the surface-grid gradient against a fixed sun direction gives specular strength, squared and stamped as glints, so sun glitter sparks alive as the surface sways.
Best forSunrise and night-beach campaign backgrounds
dotpowImageData

<main class="stage">
<div class="sg" id="sg">
<p class="sg__hint">
<svg class="sg__ico" viewBox="0 0 256 256" aria-hidden="true"><g fill="currentColor"><path d="M16 120c24-32 48-32 72 0s48 32 72 0 48-32 72 0" opacity=".25"/><path d="M16 168c24-32 48-32 72 0s48 32 72 0 48-32 72 0" opacity=".15"/><path d="M228.92 49.09a112 112 0 1 0 14 84.91a8 8 0 0 0-15.5-4a96 96 0 1 1-12-72.91A8 8 0 0 1 216 71.63V40a8 8 0 0 1-8-8h-31.63a8 8 0 0 1-5.65-13.09ZM64 104a12 12 0 1 1 12 12a12 12 0 0 1-12-12m40 64a12 12 0 1 1 12 12a12 12 0 0 1-12-12m72-16a16 16 0 1 1 16 16a16 16 0 0 1-16-16" opacity=".9"/></g></svg>
<span>Raises the dot of surface gradient and sun direction to a power to stamp only the glints — drag to move the sun</span>
</p>
<div class="sg__field" id="field" role="application" aria-label="Specular highlight playground" tabindex="0">
<canvas class="sg__cv" id="cv"></canvas>
<b class="sg__badge" aria-hidden="true"><span class="sg__badgeNum" id="shinyVal">shininess 48</span><span class="sg__badgeUnit" id="windVal">wind 1.0</span></b>
</div>
</div>
</main>@use "../../../../site/static/demo-tokens" as *;
// 반사 하이라이트 — 수면 법선과 태양 방향의 내적을 shininess 로 제곱해 문턱 넘는 칸만 glint 로 찍는다.
// 움직임은 전부 캔버스 rAF 안에 있다. @keyframes 를 두지 않는다(077 방식).
// 색은 전부 토큰 또는 mix() 로컬 변수(BD26) — 헥스 리터럴 금지.
// 캔버스가 쓰는 색은 커스텀 프로퍼티로 내려보낸다 — 값은 이 파일 한 곳에만 둔다.
$sg-water0: mix($subject-blue-deep, $stage-paper, 58%); // 바탕 물색 — 진한 파랑
$sg-water1: mix($subject-blue, $stage-paper, 64%); // 바탕 물색 — 파랑(밝은 쪽)
$sg-glint: mix($subject-cream, $stage-paper, 90%); // 반짝이 — 크림
$sg-glint2: $subject-cream; // 반짝이 정점 — 밝은 크림
$duration: $dur-loop;
$easing: $ease-spring;
$color: $sg-glint2;
@include stage($stage-paper);
.sg {
--water0: #{$sg-water0};
--water1: #{$sg-water1};
--glint: #{$sg-glint};
--glint2: #{$sg-glint2};
display: flex; flex-direction: column; gap: $sp-2;
width: 100%; max-width: 424px;
}
.sg__hint {
display: flex; align-items: center; gap: $sp-1; margin: 0;
font-weight: 700; font-size: clamp(10px, 2.8vw, 12px); line-height: 1.35;
color: $subject-ink;
}
.sg__ico { width: 16px; height: 16px; flex: 0 0 auto; color: $subject-blue; }
.sg__field {
position: relative; height: 208px;
border-radius: $r-card; overflow: hidden;
background: $sg-water0;
box-shadow: inset 0 0 0 1px rgba($subject-ink, .16);
cursor: crosshair; touch-action: none;
}
.sg__field:focus-visible { outline: 2px solid $subject-blue; outline-offset: 2px; }
.sg__cv { display: block; width: 100%; height: 100%; }
.sg__badge {
position: absolute; right: $sp-2; top: $sp-2;
display: flex; align-items: baseline; gap: $sp-1;
padding: $sp-1 $sp-2; border-radius: $r-pill;
background: rgba($subject-ink, .78);
color: $subject-cream; font-weight: 700; font-size: 11px;
}
.sg__badgeNum { font-size: 13px; color: $stage-yellow; }
.sg__badgeUnit { font-weight: 700; }
@media (max-width: 340px) {
.sg { gap: $sp-1; }
.sg__field { height: 124px; }
.sg__badge { font-size: 10px; padding: 0 $sp-1; }
.sg__badgeNum { font-size: 11px; }
.sg__hint { font-size: 10px; }
}
// reduce — 루프가 아예 안 돈다. 태양 반짝이가 박힌 정적 한 장이 남으므로
// 끌 수 있다는 신호(커서)만 거둔다.
@media (prefers-reduced-motion: reduce) {
.sg.is-still .sg__field { cursor: default !important; }
.sg.is-still .sg__badge { opacity: .92 !important; }
}html, body {
margin: 0;
overflow: hidden;
}
.stage {
box-sizing: border-box;
min-height: 100vh;
display: grid;
place-items: center;
margin: 0;
background: #ffffff;
font-family: -apple-system, "Segoe UI", "Noto Sans KR", sans-serif;
padding: clamp(8px, 4vw, 24px);
}
.sg {
--water0: rgb(44.2745098039%, 59.968627451%, 94.768627451%);
--water1: rgb(47.7960784314%, 63.3568627451%, 97.7411764706%);
--glint: rgb(100%, 97.1764705882%, 91.1764705882%);
--glint2: #fff7e6;
display: flex;
flex-direction: column;
gap: 8px;
width: 100%;
max-width: 424px;
}
.sg__hint {
display: flex;
align-items: center;
gap: 4px;
margin: 0;
font-weight: 700;
font-size: clamp(10px, 2.8vw, 12px);
line-height: 1.35;
color: #17141a;
}
.sg__ico {
width: 16px;
height: 16px;
flex: 0 0 auto;
color: #2f6df6;
}
.sg__field {
position: relative;
height: 208px;
border-radius: 16px;
overflow: hidden;
background: rgb(44.2745098039%, 59.968627451%, 94.768627451%);
box-shadow: inset 0 0 0 1px rgba(23, 20, 26, 0.16);
cursor: crosshair;
touch-action: none;
}
.sg__field:focus-visible {
outline: 2px solid #2f6df6;
outline-offset: 2px;
}
.sg__cv {
display: block;
width: 100%;
height: 100%;
}
.sg__badge {
position: absolute;
right: 8px;
top: 8px;
display: flex;
align-items: baseline;
gap: 4px;
padding: 4px 8px;
border-radius: 999px;
background: rgba(23, 20, 26, 0.78);
color: #fff7e6;
font-weight: 700;
font-size: 11px;
}
.sg__badgeNum {
font-size: 13px;
color: #ffd23f;
}
.sg__badgeUnit {
font-weight: 700;
}
@media (max-width: 340px) {
.sg {
gap: 4px;
}
.sg__field {
height: 124px;
}
.sg__badge {
font-size: 10px;
padding: 0 4px;
}
.sg__badgeNum {
font-size: 11px;
}
.sg__hint {
font-size: 10px;
}
}
@media (prefers-reduced-motion: reduce) {
.sg.is-still .sg__field {
cursor: default !important;
}
.sg.is-still .sg__badge {
opacity: 0.92 !important;
}
}// 반사 하이라이트 — 01 과 같은 뿌리(정현파 6개 mulberry32(7) + Gerstner 처짐)의 2D 파도장에서
// 중앙차분으로 법선(nx, ny, 1)을 근사하고, 태양(광원) 방향 L 과의 내적 dot(N,L) 을 shininess 로
// 제곱해(pow) 스페큘러 세기를 얻는다. 세기가 문턱을 넘는 칸만 반짝이(glint)로 찍어
// "찰나의 빛무리"를 만든다 — 램프 전체를 밝히는 것과 다르다. 태양 방향은 포인터 드래그로 조절.
var root = document.getElementById('sg');
var field = document.getElementById('field');
var cv = document.getElementById('cv');
var shinyVal = document.getElementById('shinyVal');
var windVal = document.getElementById('windVal');
var ctx = cv.getContext('2d');
var css = getComputedStyle(root);
function v(name) { return css.getPropertyValue(name).trim(); }
var WATER0 = v('--water0'), WATER1 = v('--water1'); // 바탕 물색 — 억제된 파랑 램프
var GLINT = v('--glint'), GLINT2 = v('--glint2'); // 반짝이 — 크림 → 밝은 크림
var COLS = 110; // 수면 격자 가로 칸 수(01 과 동일)
var STEP = 3; // 격자 한 칸이 렌더 버퍼에서 차지하는 픽셀
var NW = 6; // 겹칠 정현파 개수
var SHINY = 48; // 스페큘러 지수(shininess) — 클수록 반짝이가 더 좁고 날카롭다
function mulberry32(a) {
return function () {
a |= 0; a = (a + 0x6D2B79F5) | 0;
var t = Math.imul(a ^ (a >>> 15), 1 | a);
var u = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((u ^ (u >>> 14)) >>> 0) / 4294967296;
};
}
var rng = mulberry32(7);
var WAVES = [];
(function () {
var lam = 34;
for (var i = 0; i < NW; i++) {
var ang = rng() * Math.PI * 2;
WAVES.push({
lam: lam,
freq: (Math.PI * 2) / lam,
dirX: Math.cos(ang), dirY: Math.sin(ang),
amp: 0.58 / (i * 0.62 + 1),
spd: 0.55 + rng() * 0.25,
ph: rng() * Math.PI * 2
});
lam *= 0.55;
}
})();
for (var w = 0; w < NW; w++) {
WAVES[w].om = WAVES[w].spd * 3.6 * Math.sqrt(1 / WAVES[w].lam) * 6;
}
var reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
var W = 0, H = 0, dpr = 1, ROWS = 0;
var hgt = null; // 격자 높이(Float32Array)
var buf = null, bctx = null, out = null;
var RW = 0, RH = 0;
var raf = 0, auto = true, nowSec = 0;
var wind = 1.0, windT = 1.0;
var windAng = 0.5, windAngT = 0.5;
var lastPX = -1, lastPY = -1, lastPT = 0;
// 태양(광원) 방향 — 단위벡터(lx, ly, lz). 자동 모드에서는 천천히 원을 그리고, 드래그 중엔 포인터를 따라간다.
var sunAng = 0.9, sunAngT = 0.9;
var sunZ = 0.62, sunZT = 0.62; // z 성분(하늘 쪽 기울기) — 클수록 광원이 수직에 가깝다(반짝이가 넓게 퍼짐)
var dragging = false;
function hex2rgb(s) {
var pm = /^\s*rgb\(\s*([\d.]+)%\s*,\s*([\d.]+)%\s*,\s*([\d.]+)%\s*\)\s*$/.exec(s);
if (pm) return [Math.round(pm[1] * 2.55), Math.round(pm[2] * 2.55), Math.round(pm[3] * 2.55)];
s = s.replace('#', '');
if (s.length === 3) s = s[0] + s[0] + s[1] + s[1] + s[2] + s[2];
var n = parseInt(s, 16);
return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
}
var RW0 = hex2rgb(WATER0), RW1 = hex2rgb(WATER1);
var RG = hex2rgb(GLINT), RG2 = hex2rgb(GLINT2);
function fit() {
var r = field.getBoundingClientRect();
dpr = window.devicePixelRatio || 1;
W = r.width; H = r.height;
cv.width = Math.round(W * dpr);
cv.height = Math.round(H * dpr);
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ROWS = Math.max(40, Math.round(COLS * H / W));
hgt = new Float32Array(COLS * ROWS);
RW = COLS * STEP; RH = ROWS * STEP;
buf = document.createElement('canvas');
buf.width = RW; buf.height = RH;
bctx = buf.getContext('2d');
out = bctx.createImageData(RW, RH);
}
// 파도장 높이 합성 — 01 과 같은 뿌리
function fieldcalc(t, wstr, wang) {
var i = 0;
for (var y = 0; y < ROWS; y++) {
for (var x = 0; x < COLS; x++, i++) {
var h = 0;
for (var w2 = 0; w2 < NW; w2++) {
var WV = WAVES[w2];
var da = wang * 0.5;
var dx = WV.dirX * Math.cos(da) - WV.dirY * Math.sin(da);
var dy = WV.dirX * Math.sin(da) + WV.dirY * Math.cos(da);
var ph = (x * dx + y * dy) * WV.freq * 0.62 + t * WV.om + WV.ph;
h += WV.amp * wstr * Math.sin(ph);
}
hgt[i] = h;
}
}
}
// 렌더 — 바탕은 억제된 물색 램프, 그 위에 중앙차분 법선과 태양 벡터의 내적을 shininess 로 제곱해
// threshold 넘는 칸만 glint 로 찍는다. 경계 칸(x/y 끝)은 차분을 안쪽으로만 잡아 배열 밖을 읽지 않는다.
function render() {
var o = out.data;
var lx = Math.cos(sunAng) * (1 - sunZ), ly = Math.sin(sunAng) * (1 - sunZ), lz = sunZ + 0.3;
var llen = Math.sqrt(lx * lx + ly * ly + lz * lz);
lx /= llen; ly /= llen; lz /= llen;
for (var y = 0; y < ROWS; y++) {
var row = y * COLS;
var y0 = y > 0 ? y - 1 : y, y1 = y < ROWS - 1 ? y + 1 : y;
for (var x = 0; x < COLS; x++) {
var idx = row + x;
var x0 = x > 0 ? x - 1 : x, x1 = x < COLS - 1 ? x + 1 : x;
// 중앙차분 기울기 — 법선(nx, ny, nz) 근사. 분모(x1-x0, y1-y0)가 0 이 되는 경계는 위에서 안쪽 클램프로 방지.
var gx = (hgt[row + x1] - hgt[row + x0]) / Math.max(1, x1 - x0);
var gy = (hgt[y1 * COLS + x] - hgt[y0 * COLS + x]) / Math.max(1, y1 - y0);
var nx = -gx * 5.2, ny = -gy * 5.2, nz = 1;
var nlen = Math.sqrt(nx * nx + ny * ny + nz * nz);
nx /= nlen; ny /= nlen; nz /= nlen;
var d = nx * lx + ny * ly + nz * lz;
if (d < 0) d = 0;
var spec = Math.pow(d, SHINY); // dot(N,L)^shininess — 좁고 날카로운 반짝이
// 바탕 물색 — 높이를 낮은 대비로만 섞어 캔버스가 완전 단색이 되지 않게
var u = hgt[idx] * 0.6 + 0.5;
if (u < 0) u = 0; else if (u > 1) u = 1;
var r = RW0[0] + (RW1[0] - RW0[0]) * u;
var g = RW0[1] + (RW1[1] - RW0[1]) * u;
var b = RW0[2] + (RW1[2] - RW0[2]) * u;
if (spec > 0.02) {
var f = spec > 1 ? 1 : spec;
var top = f > 0.6 ? (f - 0.6) / 0.4 : 0;
var gr = RG[0] + (RG2[0] - RG[0]) * top;
var gg = RG[1] + (RG2[1] - RG[1]) * top;
var gb = RG[2] + (RG2[2] - RG[2]) * top;
r = r * (1 - f) + gr * f;
g = g * (1 - f) + gg * f;
b = b * (1 - f) + gb * f;
}
for (var sy = 0; sy < STEP; sy++) {
var base = ((y * STEP + sy) * RW + x * STEP) * 4;
for (var sx = 0; sx < STEP; sx++, base += 4) {
o[base] = r;
o[base + 1] = g;
o[base + 2] = b;
o[base + 3] = 255;
}
}
}
}
bctx.putImageData(out, 0, 0);
ctx.drawImage(buf, 0, 0, W, H);
}
function frame(now) {
nowSec = now / 1000;
if (auto) {
var th = nowSec * 0.31;
windT = 1.05 + Math.sin(th * 0.9 + 0.4) * 0.55 + Math.sin(th * 2.3) * 0.12;
windAngT = 0.5 + Math.sin(th * 0.42) * 0.85;
}
if (!dragging) {
sunAngT = nowSec * 0.18; // 자동 모드 — 태양이 천천히 원을 그린다
}
wind += (windT - wind) * 0.05;
windAng += (windAngT - windAng) * 0.05;
sunAng += (sunAngT - sunAng) * 0.06;
sunZ += (sunZT - sunZ) * 0.06;
fieldcalc(nowSec, wind, windAng);
render();
windVal.textContent = 'wind ' + wind.toFixed(2);
raf = requestAnimationFrame(frame);
}
// 정지판 — 루프 없이 시드가 정한 한 시각의 파도장 + 태양 위치를 계산해 반짝이가 박힌 정적 한 장
function still() {
fieldcalc(7.3, 1.35, 0.5);
sunAng = 0.9; sunZ = 0.62;
render();
}
function localXY(e) {
var r = field.getBoundingClientRect();
return [e.clientX - r.left, e.clientY - r.top];
}
field.addEventListener('pointerdown', function (e) {
dragging = true;
field.setPointerCapture(e.pointerId);
var p = localXY(e);
sunAngT = Math.atan2(p[1] - H / 2, p[0] - W / 2);
sunZT = Math.max(0.1, Math.min(0.95, 1 - Math.sqrt((p[0] - W / 2) * (p[0] - W / 2) + (p[1] - H / 2) * (p[1] - H / 2)) / (W * 0.6)));
});
field.addEventListener('pointermove', function (e) {
var p = localXY(e);
var t = performance.now();
if (dragging) {
sunAngT = Math.atan2(p[1] - H / 2, p[0] - W / 2);
sunZT = Math.max(0.1, Math.min(0.95, 1 - Math.sqrt((p[0] - W / 2) * (p[0] - W / 2) + (p[1] - H / 2) * (p[1] - H / 2)) / (W * 0.6)));
}
if (lastPX >= 0 && t > lastPT) {
var vx = p[0] - lastPX, vy = p[1] - lastPY;
var sp2 = Math.sqrt(vx * vx + vy * vy);
if (sp2 > 0.5) {
windT = Math.max(0.35, Math.min(2.1, 0.9 + sp2 * 0.02));
windAngT = Math.atan2(vy, vx) * 0.16;
}
}
lastPX = p[0]; lastPY = p[1]; lastPT = t;
auto = false;
});
field.addEventListener('pointerup', function () { dragging = false; });
field.addEventListener('pointerleave', function () {
auto = true;
dragging = false;
lastPX = -1;
});
field.addEventListener('keydown', function (e) {
var d = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] }[e.key];
if (!d) return;
e.preventDefault();
auto = false;
dragging = true;
sunAngT = sunAngT + d[0] * 0.2;
sunZT = Math.max(0.1, Math.min(0.95, sunZT + d[1] * 0.08));
if (reduce) { fieldcalc(nowSec || 3.1, windT, windAngT); render(); }
});
window.addEventListener('resize', function () { fit(); if (reduce) still(); });
fit();
shinyVal.textContent = 'shininess ' + SHINY;
if (reduce) {
root.classList.add('is-still');
still();
} else {
raf = requestAnimationFrame(frame);
}// SpecularGlitter — vanilla 판(run/313/demo/04-ocean-specular-glitter/index.html) 의 React 포트.
// 01 과 같은 뿌리(정현파 6개, 시드 7)의 2D 파도장에서 중앙차분으로 법선을 근사하고
// 태양(광원) 방향과의 내적을 shininess 로 제곱해 문턱 넘는 칸만 glint 로 찍는다.
// 태양 방향은 자동 순환 + 포인터 드래그. 움직임은 캔버스 rAF 루프가 전부이므로 @keyframes 는 없다.
import { useEffect, useRef } from "react";
import type { CSSProperties } from "react";
import styles from "./SpecularGlitter.module.scss";
export type SpecularGlitterProps = {
duration?: string;
easing?: string;
color?: string;
};
type Vars = CSSProperties & { "--duration"?: string; "--easing"?: string; "--color"?: string };
type Box<T> = { current: T };
type PointerLikeEvent = { clientX: number; clientY: number; pointerId: number };
const COLS = 110;
const STEP = 3;
const NW = 6;
const SHINY = 48;
function mulberry32(a: number): () => number {
return function () {
a |= 0; a = (a + 0x6D2B79F5) | 0;
const t = Math.imul(a ^ (a >>> 15), 1 | a);
const u = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((u ^ (u >>> 14)) >>> 0) / 4294967296;
};
}
type Wave = {
lam: number; freq: number; dirX: number; dirY: number;
amp: number; spd: number; ph: number; om: number;
};
function buildWaves(): Wave[] {
const rng = mulberry32(7);
const out: Wave[] = [];
let lam = 34;
for (let i = 0; i < NW; i++) {
const ang = rng() * Math.PI * 2;
const wv: Wave = {
lam,
freq: (Math.PI * 2) / lam,
dirX: Math.cos(ang),
dirY: Math.sin(ang),
amp: 0.58 / (i * 0.62 + 1),
spd: 0.55 + rng() * 0.25,
ph: rng() * Math.PI * 2,
om: 0,
};
wv.om = wv.spd * 3.6 * Math.sqrt(1 / wv.lam) * 6;
out.push(wv);
lam *= 0.55;
}
return out;
}
function hex2rgb(s: string): [number, number, number] {
const pm = /^\s*rgb\(\s*([\d.]+)%\s*,\s*([\d.]+)%\s*,\s*([\d.]+)%\s*\)\s*$/.exec(s);
if (pm) return [Math.round(+pm[1] * 2.55), Math.round(+pm[2] * 2.55), Math.round(+pm[3] * 2.55)];
let t = s.replace("#", "");
if (t.length === 3) t = t[0] + t[0] + t[1] + t[1] + t[2] + t[2];
const n = parseInt(t, 16);
return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
}
export default function SpecularGlitter({
duration = "2s",
easing = "cubic-bezier(.2, .8, .2, 1)",
color = "#fff7e6",
}: SpecularGlitterProps) {
const rootRef = useRef<HTMLDivElement | null>(null);
const fieldRef = useRef<HTMLDivElement | null>(null);
const cvRef = useRef<HTMLCanvasElement | null>(null);
const ctxRef = useRef<CanvasRenderingContext2D | null>(null);
const shinyValRef = useRef<HTMLSpanElement | null>(null);
const windValRef = useRef<HTMLSpanElement | null>(null);
const wavesRef = useRef<Wave[] | null>(null);
const sizeRef = useRef({ w: 0, h: 0 }) as Box<{ w: number; h: number }>;
const rafRef = useRef(0) as Box<number>;
const stillRef = useRef(false) as Box<boolean>;
type St = {
rows: number; rw: number; rh: number;
hgt: Float32Array | null;
out: ImageData | null;
bctx: CanvasRenderingContext2D | null;
buf: HTMLCanvasElement | null;
auto: boolean; dragging: boolean;
wind: number; windT: number;
windAng: number; windAngT: number;
sunAng: number; sunAngT: number;
sunZ: number; sunZT: number;
lastPX: number; lastPY: number; lastPT: number;
water0: [number, number, number] | null;
water1: [number, number, number] | null;
glint: [number, number, number] | null;
glint2: [number, number, number] | null;
};
const stRef = useRef({
rows: 0, rw: 0, rh: 0,
hgt: null, out: null, bctx: null, buf: null,
auto: true, dragging: false,
wind: 1.0, windT: 1.0,
windAng: 0.5, windAngT: 0.5,
sunAng: 0.9, sunAngT: 0.9,
sunZ: 0.62, sunZT: 0.62,
lastPX: -1, lastPY: -1, lastPT: 0,
water0: null, water1: null, glint: null, glint2: null,
} as St) as Box<St>;
const vars: Vars = { "--duration": duration, "--easing": easing, "--color": color };
function reduced(): boolean {
return window.matchMedia("(prefers-reduced-motion: reduce)").matches;
}
function fit(): void {
const field = fieldRef.current, cv = cvRef.current;
if (!field || !cv) return;
const r = field.getBoundingClientRect();
const dpr = window.devicePixelRatio || 1;
sizeRef.current.w = r.width;
sizeRef.current.h = r.height;
cv.width = Math.round(r.width * dpr);
cv.height = Math.round(r.height * dpr);
const ctx = ctxRef.current;
if (ctx) ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
const st = stRef.current;
st.rows = Math.max(40, Math.round(COLS * r.height / r.width));
st.hgt = new Float32Array(COLS * st.rows);
st.rw = COLS * STEP; st.rh = st.rows * STEP;
const buf = document.createElement("canvas");
buf.width = st.rw; buf.height = st.rh;
st.buf = buf;
st.bctx = buf.getContext("2d");
if (st.bctx) st.out = st.bctx.createImageData(st.rw, st.rh);
}
function fieldcalc(t: number, wstr: number, wang: number): void {
const st = stRef.current;
const WV = wavesRef.current;
if (!st.hgt || !WV) return;
let i = 0;
for (let y = 0; y < st.rows; y++) {
for (let x = 0; x < COLS; x++, i++) {
let h = 0;
for (let k = 0; k < NW; k++) {
const wv = WV[k];
const da = wang * 0.5;
const dx = wv.dirX * Math.cos(da) - wv.dirY * Math.sin(da);
const dy = wv.dirX * Math.sin(da) + wv.dirY * Math.cos(da);
const ph = (x * dx + y * dy) * wv.freq * 0.62 + t * wv.om + wv.ph;
h += wv.amp * wstr * Math.sin(ph);
}
st.hgt[i] = h;
}
}
}
// 중앙차분 법선 · 태양 내적 제곱 · 문턱 넘는 칸만 glint
function render(): void {
const st = stRef.current;
const ctx = ctxRef.current;
if (!st.out || !st.bctx || !st.buf || !ctx || !st.hgt) return;
if (!st.water0 || !st.water1 || !st.glint || !st.glint2) return;
const o = st.out.data;
const RW0 = st.water0, RW1 = st.water1, RG = st.glint, RG2 = st.glint2;
let lx = Math.cos(st.sunAng) * (1 - st.sunZ), ly = Math.sin(st.sunAng) * (1 - st.sunZ), lz = st.sunZ + 0.3;
const llen = Math.sqrt(lx * lx + ly * ly + lz * lz);
lx /= llen; ly /= llen; lz /= llen;
for (let y = 0; y < st.rows; y++) {
const row = y * COLS;
const y0 = y > 0 ? y - 1 : y, y1 = y < st.rows - 1 ? y + 1 : y;
for (let x = 0; x < COLS; x++) {
const idx = row + x;
const x0 = x > 0 ? x - 1 : x, x1 = x < COLS - 1 ? x + 1 : x;
const gx = (st.hgt[row + x1] - st.hgt[row + x0]) / Math.max(1, x1 - x0);
const gy = (st.hgt[y1 * COLS + x] - st.hgt[y0 * COLS + x]) / Math.max(1, y1 - y0);
let nx = -gx * 5.2, ny = -gy * 5.2, nz = 1;
const nlen = Math.sqrt(nx * nx + ny * ny + nz * nz);
nx /= nlen; ny /= nlen; nz /= nlen;
let d = nx * lx + ny * ly + nz * lz;
if (d < 0) d = 0;
const spec = Math.pow(d, SHINY);
let u = st.hgt[idx] * 0.6 + 0.5;
if (u < 0) u = 0; else if (u > 1) u = 1;
let r = RW0[0] + (RW1[0] - RW0[0]) * u;
let g = RW0[1] + (RW1[1] - RW0[1]) * u;
let b = RW0[2] + (RW1[2] - RW0[2]) * u;
if (spec > 0.02) {
const f = spec > 1 ? 1 : spec;
const top = f > 0.6 ? (f - 0.6) / 0.4 : 0;
const gr = RG[0] + (RG2[0] - RG[0]) * top;
const gg = RG[1] + (RG2[1] - RG[1]) * top;
const gb = RG[2] + (RG2[2] - RG[2]) * top;
r = r * (1 - f) + gr * f;
g = g * (1 - f) + gg * f;
b = b * (1 - f) + gb * f;
}
for (let sy = 0; sy < STEP; sy++) {
let base = ((y * STEP + sy) * st.rw + x * STEP) * 4;
for (let sx = 0; sx < STEP; sx++, base += 4) {
o[base] = r;
o[base + 1] = g;
o[base + 2] = b;
o[base + 3] = 255;
}
}
}
}
st.bctx.putImageData(st.out, 0, 0);
ctx.drawImage(st.buf, 0, 0, sizeRef.current.w, sizeRef.current.h);
}
function frame(now: number): void {
const st = stRef.current;
const sec = now / 1000;
if (st.auto) {
const th = sec * 0.31;
st.windT = 1.05 + Math.sin(th * 0.9 + 0.4) * 0.55 + Math.sin(th * 2.3) * 0.12;
st.windAngT = 0.5 + Math.sin(th * 0.42) * 0.85;
}
if (!st.dragging) st.sunAngT = sec * 0.18;
st.wind += (st.windT - st.wind) * 0.05;
st.windAng += (st.windAngT - st.windAng) * 0.05;
st.sunAng += (st.sunAngT - st.sunAng) * 0.06;
st.sunZ += (st.sunZT - st.sunZ) * 0.06;
fieldcalc(sec, st.wind, st.windAng);
render();
if (windValRef.current) windValRef.current.textContent = "바람 " + st.wind.toFixed(2);
rafRef.current = requestAnimationFrame(frame);
}
function localXY(e: PointerLikeEvent): [number, number] {
const field = fieldRef.current;
if (!field) return [0, 0];
const r = field.getBoundingClientRect();
return [e.clientX - r.left, e.clientY - r.top];
}
function aimSun(px: number, py: number): void {
const st = stRef.current;
const w = sizeRef.current.w, h = sizeRef.current.h;
st.sunAngT = Math.atan2(py - h / 2, px - w / 2);
const dist = Math.sqrt((px - w / 2) * (px - w / 2) + (py - h / 2) * (py - h / 2));
st.sunZT = Math.max(0.1, Math.min(0.95, 1 - dist / (w * 0.6)));
}
function onPointerDown(e: PointerLikeEvent & { currentTarget: HTMLDivElement }): void {
const st = stRef.current;
st.dragging = true;
try { e.currentTarget.setPointerCapture(e.pointerId); } catch { /* noop */ }
const [px, py] = localXY(e);
aimSun(px, py);
}
function onPointerMove(e: PointerLikeEvent): void {
const st = stRef.current;
const [px, py] = localXY(e);
if (st.dragging) aimSun(px, py);
const t = performance.now();
if (st.lastPX >= 0 && t > st.lastPT) {
const vx = px - st.lastPX, vy = py - st.lastPY;
const sp = Math.sqrt(vx * vx + vy * vy);
if (sp > 0.5) {
st.windT = Math.max(0.35, Math.min(2.1, 0.9 + sp * 0.02));
st.windAngT = Math.atan2(vy, vx) * 0.16;
}
}
st.lastPX = px; st.lastPY = py; st.lastPT = t;
st.auto = false;
}
function onPointerUp(): void {
stRef.current.dragging = false;
}
function onPointerLeave(): void {
const st = stRef.current;
st.auto = true;
st.dragging = false;
st.lastPX = -1;
}
function onResize(): void {
fit();
if (reduced()) {
fieldcalc(7.3, 1.35, 0.5);
render();
}
}
useEffect(() => {
const cv = cvRef.current;
const root = rootRef.current;
if (!cv || !root) return;
ctxRef.current = cv.getContext("2d");
if (!ctxRef.current) return;
wavesRef.current = buildWaves();
const cs = getComputedStyle(root);
const tok = (name: string) => cs.getPropertyValue(name).trim();
const st = stRef.current;
st.water0 = hex2rgb(tok("--water0"));
st.water1 = hex2rgb(tok("--water1"));
st.glint = hex2rgb(tok("--glint"));
st.glint2 = hex2rgb(tok("--glint2"));
fit();
window.addEventListener("resize", onResize);
if (reduced()) {
stillRef.current = true;
fieldcalc(7.3, 1.35, 0.5);
st.sunAng = 0.9; st.sunZ = 0.62;
render();
} else {
rafRef.current = requestAnimationFrame(frame);
}
return () => {
window.removeEventListener("resize", onResize);
cancelAnimationFrame(rafRef.current);
};
}, []);
const cls = [styles.root, stillRef.current ? styles.isStill : ""].filter(Boolean).join(" ");
return (
<main className={styles.stage}>
<div className={cls} ref={rootRef} style={vars}>
<p className={styles.hint}>
<svg className={styles.ico} viewBox="0 0 256 256" aria-hidden="true"><g fill="currentColor"><path d="M16 120c24-32 48-32 72 0s48 32 72 0 48-32 72 0" opacity=".25"/><path d="M16 168c24-32 48-32 72 0s48 32 72 0 48-32 72 0" opacity=".15"/><path d="M228.92 49.09a112 112 0 1 0 14 84.91a8 8 0 0 0-15.5-4a96 96 0 1 1-12-72.91A8 8 0 0 1 216 71.63V40a8 8 0 0 1-8-8h-31.63a8 8 0 0 1-5.65-13.09ZM64 104a12 12 0 1 1 12 12a12 12 0 0 1-12-12m40 64a12 12 0 1 1 12 12a12 12 0 0 1-12-12m72-16a16 16 0 1 1 16 16a16 16 0 0 1-16-16" opacity=".9"/></g></svg>
<span>수면 기울기와 태양 방향의 내적을 제곱해 반짝이만 찍습니다 — 드래그로 태양을 옮기세요</span>
</p>
<div
className={styles.field}
ref={fieldRef}
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={onPointerUp}
onPointerLeave={onPointerLeave}
>
<canvas className={styles.cv} ref={cvRef}></canvas>
<b className={styles.badge} aria-hidden="true"><span className={styles.badgeNum} ref={shinyValRef}>광택 {SHINY}</span><span className={styles.badgeUnit} ref={windValRef}>바람 1.0</span></b>
</div>
</div>
</main>
);
}04 Specular highlight — sun glitter — Measured area 41.906% · moving frames 23/23Original by GODRICH · SCSS and React ship in the zip · 9 Canvas Wave Animation Scenes: Gerstner Field
The post this demo lives in
9 Canvas Wave Animation Scenes: Gerstner FieldA canvas wave animation is not a looping photo — every grid cell has its wave height recomputed in real time as a gerstn See all demos in this post


