09Horizon haze — the distance washed out
Aerial perspective mixes water color into sky color in proportion to each pixel's distance from the horizon while amplitude flattens with range, completing a seascape whose distance washes out.
Best forTravel, meditation, and mood-app backgrounds
lerpaerialImageData

<main class="stage">
<div class="hh" id="hh">
<p class="hh__hint">
<svg class="hh__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>The farther from the horizon, the more water color blends into sky color and amplitude flattens — an aerial perspective; move the mouse to shift the horizon</span>
</p>
<div class="hh__field" id="field" role="application" aria-label="Horizon haze playground" tabindex="0">
<canvas class="hh__cv" id="cv"></canvas>
<b class="hh__badge" aria-hidden="true"><span class="hh__badgeNum" id="horizonVal">horizon 34%</span><span class="hh__badgeUnit" id="windVal">wind 1.0</span></b>
</div>
</div>
</main>@use "../../../../site/static/demo-tokens" as *;
// 수평선 안개 — 원근 압축(수평선 근처는 잦은 주파수·낮은 진폭) + 거리 기반 안개 블렌드로
// 공기원근을 만든다. 움직임은 전부 캔버스 rAF 루프 안에 있다. @keyframes 를 두지 않는다
// (077 방식). 색은 전부 토큰 또는 mix() 로컬 변수(BD26) — 헥스 리터럴 금지.
// 캔버스가 쓰는 색은 커스텀 프로퍼티로 내려보낸다 — 값은 이 파일 한 곳에만 둔다.
$hh-crest: mix($subject-mint, $stage-paper, 72%);
$hh-crest2: mix($subject-sky, $stage-paper, 66%);
$hh-trough: mix($subject-blue-deep, $stage-paper, 52%);
$hh-trough2: mix($subject-blue, $stage-paper, 58%);
$hh-sky: mix($subject-lilac, $stage-paper, 58%); // 하늘 위쪽 — 옅은 라일락
$hh-sky2: mix($subject-sky, $stage-paper, 22%); // 하늘 수평선 쪽 — 밝은 하늘(안개 색)
$duration: $dur-loop;
$easing: $ease-spring;
$color: $hh-sky2;
@include stage($stage-paper);
.hh {
--crest: #{$hh-crest};
--crest-2: #{$hh-crest2};
--trough: #{$hh-trough};
--trough-2: #{$hh-trough2};
--sky: #{$hh-sky};
--sky-2: #{$hh-sky2};
display: flex; flex-direction: column; gap: $sp-2;
width: 100%; max-width: 424px;
}
.hh__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;
}
.hh__ico { width: 16px; height: 16px; flex: 0 0 auto; color: $subject-blue; }
.hh__field {
position: relative; height: 208px;
border-radius: $r-card; overflow: hidden;
background: $hh-sky2;
box-shadow: inset 0 0 0 1px rgba($subject-ink, .16);
cursor: crosshair; touch-action: none;
}
.hh__field:focus-visible { outline: 2px solid $subject-blue; outline-offset: 2px; }
.hh__cv { display: block; width: 100%; height: 100%; }
// 수평선 위치·바람 세기를 화면에도 적어 둔다 — frame() 이 갱신한다
.hh__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;
}
.hh__badgeNum { font-size: 13px; color: $stage-yellow; }
.hh__badgeUnit { font-weight: 700; }
@media (max-width: 340px) {
.hh { gap: $sp-1; }
.hh__field { height: 124px; }
.hh__badge { font-size: 10px; padding: 0 $sp-1; }
.hh__badgeNum { font-size: 11px; }
.hh__hint { font-size: 10px; }
}
// reduce — 루프가 아예 안 돈다. 안개·파도가 살아 있는 정적 한 장이 남으므로
// 끌 수 있다는 신호(커서)만 거둔다.
@media (prefers-reduced-motion: reduce) {
.hh.is-still .hh__field { cursor: default !important; }
.hh.is-still .hh__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);
}
.hh {
--crest: rgb(49.4588235294%, 87.8588235294%, 74.8705882353%);
--crest-2: rgb(62.4705882353%, 85.7647058824%, 100%);
--trough: rgb(50.0392156863%, 64.1098039216%, 95.3098039216%);
--trough-2: rgb(52.6901960784%, 66.7921568627%, 97.9529411765%);
--sky: rgb(84.0784313725%, 78.3921568627%, 100%);
--sky-2: rgb(87.4901960784%, 95.2549019608%, 100%);
display: flex;
flex-direction: column;
gap: 8px;
width: 100%;
max-width: 424px;
}
.hh__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;
}
.hh__ico {
width: 16px;
height: 16px;
flex: 0 0 auto;
color: #2f6df6;
}
.hh__field {
position: relative;
height: 208px;
border-radius: 16px;
overflow: hidden;
background: rgb(87.4901960784%, 95.2549019608%, 100%);
box-shadow: inset 0 0 0 1px rgba(23, 20, 26, 0.16);
cursor: crosshair;
touch-action: none;
}
.hh__field:focus-visible {
outline: 2px solid #2f6df6;
outline-offset: 2px;
}
.hh__cv {
display: block;
width: 100%;
height: 100%;
}
.hh__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;
}
.hh__badgeNum {
font-size: 13px;
color: #ffd23f;
}
.hh__badgeUnit {
font-weight: 700;
}
@media (max-width: 340px) {
.hh {
gap: 4px;
}
.hh__field {
height: 124px;
}
.hh__badge {
font-size: 10px;
padding: 0 4px;
}
.hh__badgeNum {
font-size: 11px;
}
.hh__hint {
font-size: 10px;
}
}
@media (prefers-reduced-motion: reduce) {
.hh.is-still .hh__field {
cursor: default !important;
}
.hh.is-still .hh__badge {
opacity: 0.92 !important;
}
}// horizon 안개 — 01 과 같은 뿌리(정현파 6개 mulberry32(7))의 파도장에 두 겹을 얹는다.
// ① 원근 감쇠 — 수평선에 가까운 행일수록 공간 주파수를 높이고(잦은 잔물결) 진폭을 낮춰
// "멀리 있는 파도는 잘게 부서져 보인다"는 원근 압축을 흉내낸다.
// ② 안개 블렌드(공기원근) — 픽셀의 수평선까지 남은 거리에 비례해 물색을 하늘색과 섞는다.
// 가까울수록(화면 아래) 안개가 거의 없고, 수평선에 닿으면 거의 하늘색 한 가지로 뭉갠다.
// horizon 위쪽은 하늘(고정 그라디언트 두 톤), horizon 자체는 포인터로 위아래 이동한다.
var root = document.getElementById('hh');
var field = document.getElementById('field');
var cv = document.getElementById('cv');
var horizonVal = document.getElementById('horizonVal');
var windVal = document.getElementById('windVal');
var ctx = cv.getContext('2d');
var css = getComputedStyle(root);
function v(name) { return css.getPropertyValue(name).trim(); }
var CREST = [v('--crest'), v('--crest-2')]; // 마루 — 민트 계열
var TROUGH = [v('--trough'), v('--trough-2')]; // 골 — 파랑 계열
var SKY = [v('--sky'), v('--sky-2')]; // 하늘 — 위 옅은 라일락 → horizon 쪽 밝은 하늘
var COLS = 110; // 파도장 가로 칸 수(01 과 동일)
var STEP = 3; // 격자 한 칸이 렌더 버퍼에서 차지하는 픽셀
var NW = 6; // 겹칠 정현파 개수(공통 물리)
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; // 파도장 높이(원근 압축 반영)
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 horizon = 0.34, horizonT = 0.34; // horizon 위치(판 세로 비율, 0=위 1=아래)
var lastPX = -1, lastPY = -1, lastPT = 0;
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 C0 = hex2rgb(CREST[0]), C1 = hex2rgb(CREST[1]);
var T0 = hex2rgb(TROUGH[0]), T1 = hex2rgb(TROUGH[1]);
var SK0 = hex2rgb(SKY[0]), SK1 = hex2rgb(SKY[1]);
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));
var n = COLS * ROWS;
hgt = new Float32Array(n);
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);
}
// 파도장 — 행마다 "수평선까지 남은 거리"로 원근 압축을 건다.
// horizonRow 보다 위(작은 y)는 바다가 아니라 하늘이므로 계산을 건너뛴다.
// dist = 1(맨 아래·가장 가까움) .. 0(horizon 바로 아래·가장 멂)
// 공간 주파수는 (1 + (1-dist)*2.4)배로 빨라지고, 진폭은 (0.15 + dist*0.85)배로 준다.
function fieldcalc(t, wstr, wang, horizonRow) {
var i = 0;
for (var y = 0; y < ROWS; y++) {
if (y < horizonRow) { i += COLS; continue; }
var dist = ROWS > horizonRow ? (y - horizonRow) / (ROWS - horizonRow) : 1;
if (dist > 1) dist = 1; else if (dist < 0) dist = 0;
var freqMul = 1 + (1 - dist) * 2.4;
var ampMul = 0.15 + dist * 0.85;
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 * freqMul + t * WV.om + WV.ph;
h += WV.amp * wstr * ampMul * Math.sin(ph);
}
hgt[i] = h;
}
}
}
// 렌더 — horizon 위는 하늘 그라디언트, 아래는 파도 색 램프 뒤 거리 기반 안개(하늘색 블렌드)를 얹는다.
// 안개 강도 fog = (1-dist)^1.6 — horizon 바로 아래가 거의 하늘색, 화면 아래는 안개가 거의 없다.
function render(horizonRow) {
var o = out.data;
for (var y = 0; y < ROWS; y++) {
var row = y * COLS;
if (y < horizonRow) {
// 하늘 — 위(짙은 라일락)에서 horizon(밝은 하늘)으로 램프
var sk = horizonRow > 0 ? y / horizonRow : 0;
var sr = SK0[0] + (SK1[0] - SK0[0]) * sk;
var sg = SK0[1] + (SK1[1] - SK0[1]) * sk;
var sb = SK0[2] + (SK1[2] - SK0[2]) * sk;
for (var x2 = 0; x2 < COLS; x2++) {
for (var sy2 = 0; sy2 < STEP; sy2++) {
var base2 = ((y * STEP + sy2) * RW + x2 * STEP) * 4;
for (var sx2 = 0; sx2 < STEP; sx2++, base2 += 4) {
o[base2] = sr; o[base2 + 1] = sg; o[base2 + 2] = sb; o[base2 + 3] = 255;
}
}
}
continue;
}
var dist = ROWS > horizonRow ? (y - horizonRow) / (ROWS - horizonRow) : 1;
if (dist > 1) dist = 1; else if (dist < 0) dist = 0;
var fog = Math.pow(1 - dist, 1.6);
for (var x = 0; x < COLS; x++) {
var i = row + x;
var h = hgt[i];
var u = h * 1.24 + 0.5;
if (u < 0) u = 0; else if (u > 1) u = 1;
var r, g, b;
if (u > 0.5) {
var k = (u - 0.5) * 2;
r = C1[0] + (C0[0] - C1[0]) * k;
g = C1[1] + (C0[1] - C1[1]) * k;
b = C1[2] + (C0[2] - C1[2]) * k;
} else {
var k2 = u * 2;
r = T0[0] + (T1[0] - T0[0]) * k2;
g = T0[1] + (T1[1] - T0[1]) * k2;
b = T0[2] + (T1[2] - T0[2]) * k2;
}
// 안개 — horizon 색(SK1, 하늘의 horizon 쪽 톤)과 섞는다
r += (SK1[0] - r) * fog;
g += (SK1[1] - g) * fog;
b += (SK1[2] - b) * fog;
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;
horizonT = 0.34 + Math.sin(th * 0.22) * 0.14; // 수평선도 천천히 오르내려 화면이 산다
}
wind += (windT - wind) * 0.05;
windAng += (windAngT - windAng) * 0.05;
horizon += (horizonT - horizon) * 0.05;
var hr = Math.round(horizon * ROWS);
fieldcalc(nowSec, wind, windAng, hr);
render(hr);
horizonVal.textContent = 'horizon ' + Math.round(horizon * 100) + '%';
windVal.textContent = 'wind ' + wind.toFixed(2);
raf = requestAnimationFrame(frame);
}
// 정지판 — 루프 없이 시드가 정한 한 시각의 안개·파도가 살아 있는 정적 한 장
function still() {
var hr = Math.round(0.34 * ROWS);
fieldcalc(7.3, 1.35, 0.5, hr);
render(hr);
}
function localXY(e) {
var r = field.getBoundingClientRect();
return [e.clientX - r.left, e.clientY - r.top];
}
field.addEventListener('pointermove', function (e) {
var p = localXY(e);
var t = performance.now();
// 포인터 세로 위치 = horizon 목표(위쪽 65%까지만 — 바다가 항상 화면 아래를 채우게)
horizonT = Math.max(0.06, Math.min(0.68, p[1] / H));
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('pointerleave', function () {
auto = true;
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;
horizonT = Math.max(0.06, Math.min(0.68, horizonT + d[1] * 0.05));
windT = Math.max(0.35, Math.min(2.1, windT + d[0] * 0.15));
if (reduce) { var hr = Math.round(horizonT * ROWS); fieldcalc(nowSec || 3.1, windT, windAngT, hr); render(hr); }
});
window.addEventListener('resize', function () { fit(); if (reduce) still(); });
fit();
if (reduce) {
root.classList.add('is-still');
still();
} else {
raf = requestAnimationFrame(frame);
}// HorizonHaze — vanilla 판(run/313/demo/09-ocean-horizon-haze/index.html) 의 React 포트.
// 01(GerstnerSum)과 같은 뿌리(정현파 6개 mulberry32(7))의 파도장에 원근 압축(수평선에
// 가까울수록 잦은 주파수·낮은 진폭)과 거리 기반 안개 블렌드(공기원근)를 얹는다.
// 수평선 위는 하늘 그라디언트, 수평선 위치는 포인터 세로 좌표로 조절한다.
import { useEffect, useRef } from "react";
import type { CSSProperties } from "react";
import styles from "./HorizonHaze.module.scss";
export type HorizonHazeProps = {
duration?: string;
easing?: string;
color?: string;
};
type Vars = CSSProperties & { "--duration"?: string; "--easing"?: string; "--color"?: string };
type Box<T> = { current: T };
type PointerMotionEvent = { clientX: number; clientY: number };
const COLS = 110;
const STEP = 3;
const NW = 6;
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 HorizonHaze({
duration = "2s",
easing = "cubic-bezier(.2, .8, .2, 1)",
color = "#bcd9f2",
}: HorizonHazeProps) {
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 horizonValRef = 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;
wind: number; windT: number;
windAng: number; windAngT: number;
horizon: number; horizonT: number;
lastPX: number; lastPY: number; lastPT: number;
c0: [number, number, number] | null;
c1: [number, number, number] | null;
t0: [number, number, number] | null;
t1: [number, number, number] | null;
sk0: [number, number, number] | null;
sk1: [number, number, number] | null;
};
const stateRef = useRef({
rows: 0, rw: 0, rh: 0,
hgt: null as Float32Array | null,
out: null as ImageData | null,
bctx: null as CanvasRenderingContext2D | null,
buf: null as HTMLCanvasElement | null,
auto: true,
wind: 1.0, windT: 1.0,
windAng: 0.5, windAngT: 0.5,
horizon: 0.34, horizonT: 0.34,
lastPX: -1, lastPY: -1, lastPT: 0,
c0: null as [number, number, number] | null,
c1: null as [number, number, number] | null,
t0: null as [number, number, number] | null,
t1: null as [number, number, number] | null,
sk0: null as [number, number, number] | null,
sk1: null as [number, number, number] | 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 = stateRef.current;
st.rows = Math.max(40, Math.round(COLS * r.height / r.width));
const n = COLS * st.rows;
st.hgt = new Float32Array(n);
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, horizonRow: number): void {
const st = stateRef.current;
const WV = wavesRef.current;
if (!st.hgt || !WV) return;
let i = 0;
for (let y = 0; y < st.rows; y++) {
if (y < horizonRow) { i += COLS; continue; }
let dist = st.rows > horizonRow ? (y - horizonRow) / (st.rows - horizonRow) : 1;
if (dist > 1) dist = 1; else if (dist < 0) dist = 0;
const freqMul = 1 + (1 - dist) * 2.4;
const ampMul = 0.15 + dist * 0.85;
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 * freqMul + t * wv.om + wv.ph;
h += wv.amp * wstr * ampMul * Math.sin(ph);
}
st.hgt[i] = h;
}
}
}
function render(horizonRow: number): void {
const st = stateRef.current;
const ctx = ctxRef.current;
if (!st.out || !st.bctx || !st.buf || !ctx || !st.hgt) return;
if (!st.c0 || !st.c1 || !st.t0 || !st.t1 || !st.sk0 || !st.sk1) return;
const o = st.out.data;
const C0 = st.c0, C1 = st.c1, T0 = st.t0, T1 = st.t1, SK0 = st.sk0, SK1 = st.sk1;
for (let y = 0; y < st.rows; y++) {
const row = y * COLS;
if (y < horizonRow) {
const sk = horizonRow > 0 ? y / horizonRow : 0;
const sr = SK0[0] + (SK1[0] - SK0[0]) * sk;
const sg = SK0[1] + (SK1[1] - SK0[1]) * sk;
const sb = SK0[2] + (SK1[2] - SK0[2]) * sk;
for (let x2 = 0; x2 < COLS; x2++) {
for (let sy2 = 0; sy2 < STEP; sy2++) {
let base2 = ((y * STEP + sy2) * st.rw + x2 * STEP) * 4;
for (let sx2 = 0; sx2 < STEP; sx2++, base2 += 4) {
o[base2] = sr; o[base2 + 1] = sg; o[base2 + 2] = sb; o[base2 + 3] = 255;
}
}
}
continue;
}
let dist = st.rows > horizonRow ? (y - horizonRow) / (st.rows - horizonRow) : 1;
if (dist > 1) dist = 1; else if (dist < 0) dist = 0;
const fog = Math.pow(1 - dist, 1.6);
for (let x = 0; x < COLS; x++) {
const i = row + x;
let u = st.hgt[i] * 1.24 + 0.5;
if (u < 0) u = 0; else if (u > 1) u = 1;
let r: number, g: number, b: number;
if (u > 0.5) {
const k = (u - 0.5) * 2;
r = C1[0] + (C0[0] - C1[0]) * k;
g = C1[1] + (C0[1] - C1[1]) * k;
b = C1[2] + (C0[2] - C1[2]) * k;
} else {
const k2 = u * 2;
r = T0[0] + (T1[0] - T0[0]) * k2;
g = T0[1] + (T1[1] - T0[1]) * k2;
b = T0[2] + (T1[2] - T0[2]) * k2;
}
r += (SK1[0] - r) * fog;
g += (SK1[1] - g) * fog;
b += (SK1[2] - b) * fog;
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 = stateRef.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;
st.horizonT = 0.34 + Math.sin(th * 0.22) * 0.14;
}
st.wind += (st.windT - st.wind) * 0.05;
st.windAng += (st.windAngT - st.windAng) * 0.05;
st.horizon += (st.horizonT - st.horizon) * 0.05;
const hr = Math.round(st.horizon * st.rows);
fieldcalc(sec, st.wind, st.windAng, hr);
render(hr);
if (horizonValRef.current) horizonValRef.current.textContent = "수평선 " + Math.round(st.horizon * 100) + "%";
if (windValRef.current) windValRef.current.textContent = "바람 " + st.wind.toFixed(2);
rafRef.current = requestAnimationFrame(frame);
}
function onPointerMove(e: PointerMotionEvent): void {
const field = fieldRef.current;
if (!field) return;
const r = field.getBoundingClientRect();
const px = e.clientX - r.left, py = e.clientY - r.top;
const t = performance.now();
const st = stateRef.current;
st.horizonT = Math.max(0.06, Math.min(0.68, py / sizeRef.current.h));
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 onPointerLeave(): void {
stateRef.current.auto = true;
stateRef.current.lastPX = -1;
}
function onResize(): void {
fit();
if (reduced()) {
const st = stateRef.current;
const hr = Math.round(0.34 * st.rows);
fieldcalc(7.3, 1.35, 0.5, hr);
render(hr);
}
}
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 = stateRef.current;
st.c0 = hex2rgb(tok("--crest"));
st.c1 = hex2rgb(tok("--crest-2"));
st.t0 = hex2rgb(tok("--trough"));
st.t1 = hex2rgb(tok("--trough-2"));
st.sk0 = hex2rgb(tok("--sky"));
st.sk1 = hex2rgb(tok("--sky-2"));
fit();
window.addEventListener("resize", onResize);
if (reduced()) {
stillRef.current = true;
const hr = Math.round(0.34 * st.rows);
fieldcalc(7.3, 1.35, 0.5, hr);
render(hr);
} 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} onPointerMove={onPointerMove} onPointerLeave={onPointerLeave}>
<canvas className={styles.cv} ref={cvRef}></canvas>
<b className={styles.badge} aria-hidden="true"><span className={styles.badgeNum} ref={horizonValRef}>수평선 34%</span><span className={styles.badgeUnit} ref={windValRef}>바람 1.0</span></b>
</div>
</div>
</main>
);
}09 Horizon haze — the distance washed out — Measured area 34.095% · 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
If you like this effect - similar demos
Creative UI03 Torus ring — the donut distance and rim light9 Ray Marching Scenes in Canvas (No WebGL)
Creative UI03 Maze — stripes kink into corridors in the middle ground9 Reaction Diffusion Simulations, No Library
Creative UI04 Afterglow diffusion — the bolt's halo bleeding through a pixel buffer9 Lightning Effect Background Scenes, No WebGL