08Organic texture panel — capturing one frame as a card background
Freeze the canvas the moment the network finishes growing, lower its opacity, and even a static image reads as a hand-drawn organic texture for cards or sections.
Best forProduct-card backgrounds, about-section texture
ImageDatarequestAnimationFrame

<main class="stage">
<div class="sm is-demo" id="smRoot">
<p class="sm__hint">
<span>Freeze the canvas the moment the network finishes growing, lower its opacity, and even a static image reads as a hand-drawn organic texture for cards or sections</span>
</p>
<div class="sm__field" id="smField" role="application" aria-label="Organic Texture Panel Slime Demo" tabindex="0">
<canvas class="sm__cv" id="smCv"></canvas>
<div class="sm__veil" id="smVeil" aria-hidden="true">
<div class="sm__card">
<p class="sm__card-t">Organic Section</p>
<p class="sm__card-s">hand-drawn texture · slime network</p>
</div>
</div>
</div>
<div class="sm__bar">
<span class="sm__meta"><b class="sm__val" id="smN">0</b><span id="smUnit"> captures · frozen texture</span></span>
<span class="sm__meta sm__meta--dim">canvas · ImageData · requestAnimationFrame</span>
</div>
</div>
</main>@use "../../../../site/static/demo-tokens" as *;
// 유기체 텍스처 패널(08). @keyframes 를 두지 않는다 —
// 움직임은 전부 캔버스 rAF 루프(3센서 감지 → 회전 → 트레일 → 확산·증발 → 캡처)가 만든다.
// 무대는 크림 종이 — 여덟 번째 순환(01밤·02종이·03밀짚·04노을·05먹·06남색·07이끼).
// 질감이 UI 배경이 되는 컨셉이라 카드 목업(.sm__veil .sm__card)이 실제로 얹힌다.
$duration: $dur-loop;
$easing: $ease-spring;
$color: $subject-cream;
// ── 이 항목만의 파스텔 팔레트(밝은 계열, L 0.85 이상 — BD26 안전) ──
$sm-stage: #faf3e8; // 크림 아마 종이 무대
@include stage($sm-stage);
$sm-floor: #faf3e8; // 필드 바닥 — 무대와 같은 톤
$sm-trail: #e8d9bd; // 굳은 질감 — 파스텔 아마
$sm-acct: #f2d3c4; // 성장 중 비침 — 파스텔 살구
$sm-card: #fffcf5; // 카드 목업 면 — 종이보다 반톤 밝게
$sm-text: #453524; // 종이 위 — 짙은 갈색 글자(대비)
.sm {
--sm-floor: #{$sm-floor};
--sm-trail: #{$sm-trail};
--sm-acct: #{$sm-acct};
display: flex; flex-direction: column; gap: $sp-2;
width: 100%; max-width: 424px;
}
.sm__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: $sm-text;
}
.sm__field {
position: relative; height: 180px;
border-radius: $r-card; overflow: hidden;
background: $sm-floor;
box-shadow: inset 0 0 0 1px rgba($sm-text, .18);
}
.sm__field:focus-visible { outline: 2px solid $sm-text; outline-offset: 2px; }
.sm__cv { display: block; width: 100%; height: 100%; }
.sm__veil {
position: absolute; inset: 0;
display: flex; align-items: center; justify-content: center;
padding: $sp-3; pointer-events: none;
}
.sm__card {
max-width: 260px; width: 100%;
padding: $sp-3 $sp-4;
border-radius: $r-card;
background: rgba($sm-card, .82);
box-shadow: 0 6px 12px rgba(69, 53, 36, .18), inset 0 0 0 1px rgba(69, 53, 36, .1);
text-align: center;
}
.sm__card-t {
margin: 0;
font-weight: 700; font-size: clamp(12px, 3.4vw, 15px); line-height: 1.2;
color: $sm-text;
}
.sm__card-s {
margin: 0; margin-top: $sp-1;
font-weight: 500; font-size: clamp(9px, 2.4vw, 10px); line-height: 1.3;
color: rgba($sm-text, .72);
}
.sm__bar { display: flex; align-items: center; justify-content: space-between; gap: $sp-2; }
.sm__meta { font-size: 10px; font-weight: 700; color: rgba($sm-text, .72); }
.sm__meta--dim { font-size: 10px; font-weight: 500; color: rgba($sm-text, .72); }
@media (max-width: 340px) {
.sm { gap: $sp-1; }
.sm__field { height: 100px; }
.sm__veil { padding: $sp-2; }
.sm__card { padding: $sp-2 $sp-3; }
.sm__meta--dim { display: none; }
}
// reduce — rAF 를 돌리지 않고 캡처 한 장이 카드 배경으로 깔린 모습만 남는다.
@media (prefers-reduced-motion: reduce) {
.sm.is-still .sm__veil { pointer-events: none; }
}html, body {
margin: 0;
overflow: hidden;
}
.stage {
box-sizing: border-box;
min-height: 100vh;
display: grid;
place-items: center;
margin: 0;
background: #faf3e8;
font-family: -apple-system, "Segoe UI", "Noto Sans KR", sans-serif;
padding: clamp(8px, 4vw, 24px);
}
.sm {
--sm-floor: #faf3e8;
--sm-trail: #e8d9bd;
--sm-acct: #f2d3c4;
display: flex;
flex-direction: column;
gap: 8px;
width: 100%;
max-width: 424px;
}
.sm__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: #453524;
}
.sm__field {
position: relative;
height: 180px;
border-radius: 16px;
overflow: hidden;
background: #faf3e8;
box-shadow: inset 0 0 0 1px rgba(69, 53, 36, 0.18);
}
.sm__field:focus-visible {
outline: 2px solid #453524;
outline-offset: 2px;
}
.sm__cv {
display: block;
width: 100%;
height: 100%;
}
.sm__veil {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
padding: 12px;
pointer-events: none;
}
.sm__card {
max-width: 260px;
width: 100%;
padding: 12px 16px;
border-radius: 16px;
background: rgba(255, 252, 245, 0.82);
box-shadow: 0 6px 12px rgba(69, 53, 36, 0.18), inset 0 0 0 1px rgba(69, 53, 36, 0.1);
text-align: center;
}
.sm__card-t {
margin: 0;
font-weight: 700;
font-size: clamp(12px, 3.4vw, 15px);
line-height: 1.2;
color: #453524;
}
.sm__card-s {
margin: 0;
margin-top: 4px;
font-weight: 500;
font-size: clamp(9px, 2.4vw, 10px);
line-height: 1.3;
color: rgba(69, 53, 36, 0.72);
}
.sm__bar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.sm__meta {
font-size: 10px;
font-weight: 700;
color: rgba(69, 53, 36, 0.72);
}
.sm__meta--dim {
font-size: 10px;
font-weight: 500;
color: rgba(69, 53, 36, 0.72);
}
@media (max-width: 340px) {
.sm {
gap: 4px;
}
.sm__field {
height: 100px;
}
.sm__veil {
padding: 8px;
}
.sm__card {
padding: 8px 12px;
}
.sm__meta--dim {
display: none;
}
}
@media (prefers-reduced-motion: reduce) {
.sm.is-still .sm__veil {
pointer-events: none;
}
}// 유기체 텍스처 패널(08). Physarum 스티그머지 + 성장 캡처 → 정지 질감 재사용 —
// 시뮬레이션이 GROW_STEPS 스텝 동안 네트워크를 키운다. 다 자란 순간 필드를 snapshot 배열에
// 통째로 복사해 "정지 이미지"로 굳히고, 이후 렌더는 그 스냅샷을 카드 배경처럼 옅게 깐다.
// 위에 얹은 카드 DOM(.sm__veil .sm__card)이 "이 질감이 실제 UI 배경으로 쓰이는 모습"을 보여준다.
// .is-demo 동안은 캡처→재성장을 주기적으로 반복해 질감이 계속 새로 만들어지듯 보이게 한다.
//
// 화면이 사는 장치 — 077 캔버스 기준의 "매 프레임 계산":
// · 스냅샷 위에 앰비언트 글로우 레이어(두 옥타브 값노이즈)가 전면을 흔들어 누적면적을 채운다.
// · 캡처 경계마다 질감이 스르르 크로스페이드되며 화면이 죽지 않는다.
(function () {
// ── 변형 상수 블록 ──
var AGENTS = 1300; // 동시에 걷는 에이전트 수
var DECAY = 0.042; // 증발률
var GROW_STEPS = 130; // 질감을 굳히기 전 성장 스텝 수
// ────────────────────────────────────
var SENSOR_ANGLE = 0.5;
var SENSOR_DIST = 5.0;
var TURN = 0.5;
var STEP = 1.05;
var DEPOSIT = 4.2;
var DIFFUSE = 0.5;
var CAP = 7;
var SUBSTEPS = 3;
var FADE = 0.7; // 캡처 교체 크로스페이드 길이(초)
var root = document.getElementById('smRoot');
var field = document.getElementById('smField');
var cv = document.getElementById('smCv');
var ctx = cv.getContext('2d', { alpha: false });
var nOut = document.getElementById('smN');
function makeRand(seed) {
var st = seed >>> 0;
return function () {
st = (st + 0x6D2B79F5) >>> 0;
var t = st;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
var rand = makeRand(0x320A08);
var css = getComputedStyle(root);
function tokRGB(name) {
var s = css.getPropertyValue(name).trim();
var hx = s.length === 4
? s.charAt(1) + s.charAt(1) + s.charAt(2) + s.charAt(2) + s.charAt(3) + s.charAt(3)
: s.slice(1);
return [parseInt(hx.slice(0, 2), 16), parseInt(hx.slice(2, 4), 16), parseInt(hx.slice(4, 6), 16)];
}
var C_FLOOR = tokRGB('--sm-floor');
var C_TRAIL = tokRGB('--sm-trail');
var C_ACCT = tokRGB('--sm-acct');
var reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
var W = 0, H = 0, fw = 0, fh = 0, raf = 0, t0 = -1;
var trail, trailB, img, data;
var snapOld, snapNew; // 직전 질감 · 방금 잡은 질감
var ax, ay, ah;
var stepCount = 0;
var captureCount = 0;
var fadeT = -1; // 크로스페이드 시작 시각(-1 = 페이드 아님)
// ── 값노이즈(앰비언트 글로우용) ──
var perm = new Uint8Array(512);
(function () {
var p = [];
for (var i = 0; i < 256; i++) p.push(i);
for (var i2 = 255; i2 > 0; i2--) {
var k2 = Math.floor(rand() * (i2 + 1));
var tmp = p[i2]; p[i2] = p[k2]; p[k2] = tmp;
}
for (var i3 = 0; i3 < 512; i3++) perm[i3] = p[i3 & 255];
})();
function fade2(k) { return k * k * (3 - 2 * k); }
function vnoise(x, y) {
var xi = Math.floor(x), yi = Math.floor(y);
var xf = x - xi, yf = y - yi;
var a2 = perm[(perm[xi & 255] + yi) & 255];
var b2 = perm[(perm[(xi + 1) & 255] + yi) & 255];
var c2 = perm[(perm[xi & 255] + yi + 1) & 255];
var d2 = perm[(perm[(xi + 1) & 255] + yi + 1) & 255];
var u = fade2(xf), v = fade2(yf);
return (a2 + (b2 - a2) * u + (c2 - a2) * v + (a2 - b2 - c2 + d2) * u * v) / 255;
}
function idx(x, y) {
x = x % fw; if (x < 0) x += fw;
y = y % fh; if (y < 0) y += fh;
return (y * fw + x) | 0;
}
function clampIdx(x, y) {
x = Math.max(0, Math.min(fw - 1, Math.round(x)));
y = Math.max(0, Math.min(fh - 1, Math.round(y)));
return y * fw + x;
}
function sense(x, y) {
return trail[clampIdx(x, y)];
}
function initAgents() {
ax = new Float32Array(AGENTS); ay = new Float32Array(AGENTS); ah = new Float32Array(AGENTS);
var cx = fw / 2, cy = fh / 2, r = Math.min(fw, fh) * 0.15;
for (var i = 0; i < AGENTS; i++) {
var a = rand() * Math.PI * 2, rr = rand() * r;
ax[i] = cx + Math.cos(a) * rr;
ay[i] = cy + Math.sin(a) * rr;
ah[i] = rand() * Math.PI * 2;
}
}
function stepAgents() {
for (var i = 0; i < AGENTS; i++) {
var x = ax[i], y = ay[i], h = ah[i];
var sf = sense(x + Math.cos(h) * SENSOR_DIST, y + Math.sin(h) * SENSOR_DIST);
var sl = sense(x + Math.cos(h + SENSOR_ANGLE) * SENSOR_DIST, y + Math.sin(h + SENSOR_ANGLE) * SENSOR_DIST);
var sr = sense(x + Math.cos(h - SENSOR_ANGLE) * SENSOR_DIST, y + Math.sin(h - SENSOR_ANGLE) * SENSOR_DIST);
if (sf >= sl && sf >= sr) {
// 직진
} else if (sl > sr) {
h += TURN;
} else if (sr > sl) {
h -= TURN;
} else {
h += (rand() < 0.5 ? 1 : -1) * TURN;
}
h += (rand() - 0.5) * 0.14;
var nx = x + Math.cos(h) * STEP, ny = y + Math.sin(h) * STEP;
nx = ((nx % fw) + fw) % fw; ny = ((ny % fh) + fh) % fh;
ax[i] = nx; ay[i] = ny; ah[i] = h;
var ii = idx(Math.round(nx), Math.round(ny));
trail[ii] = Math.min(CAP, trail[ii] + DEPOSIT);
}
stepCount++;
}
function diffuseEvap() {
for (var y = 0; y < fh; y++) {
var ym = y === 0 ? fh - 1 : y - 1, yp = y === fh - 1 ? 0 : y + 1;
var rowY = y * fw, rowYm = ym * fw, rowYp = yp * fw;
for (var x = 0; x < fw; x++) {
var xm = x === 0 ? fw - 1 : x - 1, xp = x === fw - 1 ? 0 : x + 1;
var i = rowY + x;
var avg = (trail[rowY + xm] + trail[rowY + xp] + trail[rowYm + x] + trail[rowYp + x]) * 0.25;
trailB[i] = (trail[i] * (1 - DIFFUSE) + avg * DIFFUSE) * (1 - DECAY);
}
}
var t = trail; trail = trailB; trailB = t;
}
function capture() {
// 지금 필드를 통째로 굳혀 새 질감으로 삼고, 필드는 비워 다음 성장을 시작한다.
var tmp = snapOld;
snapOld = snapNew;
snapNew = tmp;
if (!snapNew) snapNew = new Float32Array(fw * fh);
snapNew.set(trail);
captureCount++;
if (nOut) nOut.textContent = String(captureCount);
for (var i = 0; i < trail.length; i++) trail[i] = 0;
stepCount = 0;
initAgents();
}
function render(t) {
var mix = 1;
if (fadeT >= 0) {
mix = (t - fadeT) / FADE;
if (mix > 1) mix = 1;
mix = mix * mix * (3 - 2 * mix);
}
for (var y = 0; y < fh; y++) {
for (var x = 0; x < fw; x++) {
var i = y * fw + x;
var j = i * 4;
// 정지 질감 두 장의 크로스페이드 — 카드 배경은 "캡처된" 필드에서 온다
var vOld = snapOld && snapOld.length === trail.length ? snapOld[i] / CAP : 0;
var vNew = snapNew ? snapNew[i] / CAP : 0;
if (vOld > 1) vOld = 1; if (vNew > 1) vNew = 1;
var v = vOld + (vNew - vOld) * mix;
var k = v * v * (3 - 2 * v);
var rr = C_FLOOR[0] + (C_TRAIL[0] - C_FLOOR[0]) * k * 0.5;
var gg = C_FLOOR[1] + (C_TRAIL[1] - C_FLOOR[1]) * k * 0.5;
var bb = C_FLOOR[2] + (C_TRAIL[2] - C_FLOOR[2]) * k * 0.5;
// 성장 중인 필드는 뚜렷하게 함께 비친다(다음 질감이 자라나는 과정)
var vGrow = trail[i] / CAP; if (vGrow > 1) vGrow = 1;
var kGrow = vGrow * vGrow * (3 - 2 * vGrow);
rr += (C_ACCT[0] - rr) * kGrow * 0.5;
gg += (C_ACCT[1] - gg) * kGrow * 0.5;
bb += (C_ACCT[2] - bb) * kGrow * 0.5;
var n1 = vnoise(x * 0.09, y * 0.09 + t * 0.9);
var n2 = vnoise(x * 0.03 + 40, y * 0.03 + t * 0.6);
var sh = (n1 - 0.5) * 30 + (n2 - 0.5) * 20;
rr += sh; gg += sh; bb += sh;
data[j] = rr; data[j + 1] = gg; data[j + 2] = bb; data[j + 3] = 255;
}
}
ctx.putImageData(img, 0, 0);
}
function fit() {
var r = field.getBoundingClientRect();
W = Math.round(r.width); H = Math.round(r.height);
fw = Math.max(96, Math.min(200, Math.round(W / 3)));
fh = Math.max(52, Math.min(120, Math.round(H / 3)));
cv.width = fw; cv.height = fh;
cv.style.width = '100%'; cv.style.height = '100%';
ctx = cv.getContext('2d', { alpha: false });
img = ctx.createImageData(fw, fh); data = img.data;
trail = new Float32Array(fw * fh); trailB = new Float32Array(fw * fh);
snapOld = null; snapNew = null;
stepCount = 0; captureCount = 0; fadeT = -1;
initAgents();
}
function stillFrame() {
for (var k = 0; k < GROW_STEPS; k++) { stepAgents(); diffuseEvap(); }
capture();
render(2.6);
}
function frame(now) {
if (t0 < 0) t0 = now;
var t = (now - t0) / 1000;
for (var i = 0; i < SUBSTEPS; i++) { stepAgents(); diffuseEvap(); }
if (stepCount >= GROW_STEPS) { capture(); fadeT = t; }
if (fadeT >= 0 && t - fadeT > FADE) fadeT = -1;
render(t);
raf = requestAnimationFrame(frame);
}
window.addEventListener('resize', function () {
fit();
if (reduce) stillFrame();
});
fit();
if (reduce) {
stillFrame();
root.classList.add('is-still');
} else {
raf = requestAnimationFrame(frame);
}
})();// VeinsTexturePanel — vanilla 판(run/320/demo/08-slime-veins-texture-panel/index.html) 의 React 포트.
// 유기체 텍스처 패널. 시뮬레이션이 GROW_STEPS 스텝 동안 네트워크를 키운 뒤 필드 전체를 snapshot
// 으로 굳혀 "정지 질감"으로 재사용한다 — 위에 얹은 카드 DOM 이 실제 UI 배경으로 쓰이는 모습을
// 보여준다. 캡처 경계마다 새·헌 질감이 크로스페이드된다.
import { useEffect, useRef, useState } from "react";
import type { CSSProperties } from "react";
import styles from "./VeinsTexturePanel.module.scss";
export type VeinsTexturePanelProps = {
duration?: string;
easing?: string;
color?: string;
agents?: number;
decay?: number;
growSteps?: number;
};
type Vars = CSSProperties & { "--duration"?: string; "--easing"?: string; "--color"?: string };
type Box<T> = { current: T };
type RGB = [number, number, number];
const FIELD_LABEL = "유기체 텍스처 패널 점균 실험판";
const SENSOR_ANGLE = 0.5;
const SENSOR_DIST = 5.0;
const TURN = 0.5;
const STEP = 1.05;
const DEPOSIT = 4.2;
const DIFFUSE = 0.5;
const CAP = 7;
const SUBSTEPS = 3;
const FADE = 0.7;
function makePRNG(seed: number): () => number {
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;
};
}
export default function VeinsTexturePanel({
duration = "2s",
easing = "cubic-bezier(.2, .8, .2, 1)",
color = "#453524",
agents = 1300,
decay = 0.042,
growSteps = 130,
}: VeinsTexturePanelProps) {
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 colRef = useRef<{ floor: RGB; trail: RGB; acct: RGB } | null>(null);
const agentsRef = useRef(agents) as Box<number>;
const decayRef = useRef(decay) as Box<number>;
const growStepsRef = useRef(growSteps) as Box<number>;
const randRef = useRef(makePRNG(0x320a08)) as Box<() => number>;
const fwRef = useRef(0) as Box<number>;
const fhRef = useRef(0) as Box<number>;
const trailRef = useRef<Float32Array>(new Float32Array(0)) as Box<Float32Array>;
const trailBRef = useRef<Float32Array>(new Float32Array(0)) as Box<Float32Array>;
const snapOldRef = useRef<Float32Array | null>(null) as Box<Float32Array | null>;
const snapNewRef = useRef<Float32Array | null>(null) as Box<Float32Array | null>;
const axRef = useRef<Float32Array>(new Float32Array(0)) as Box<Float32Array>;
const ayRef = useRef<Float32Array>(new Float32Array(0)) as Box<Float32Array>;
const ahRef = useRef<Float32Array>(new Float32Array(0)) as Box<Float32Array>;
const imgRef = useRef<ImageData | null>(null) as Box<ImageData | null>;
const permRef = useRef<Uint8Array>(new Uint8Array(512)) as Box<Uint8Array>;
const stepCountRef = useRef(0) as Box<number>;
const captureCountRef = useRef(0) as Box<number>;
const fadeTRef = useRef(-1) as Box<number>;
const rafRef = useRef(0) as Box<number>;
const [n, setN] = useState("0");
const [still, setStill] = useState(false);
const vars: Vars = { "--duration": duration, "--easing": easing, "--color": color };
function reduced(): boolean {
return window.matchMedia("(prefers-reduced-motion: reduce)").matches;
}
function tokRGB(root: HTMLDivElement, name: string): RGB {
const s = getComputedStyle(root).getPropertyValue(name).trim();
const hx = s.length === 4
? s.charAt(1) + s.charAt(1) + s.charAt(2) + s.charAt(2) + s.charAt(3) + s.charAt(3)
: s.slice(1);
return [parseInt(hx.slice(0, 2), 16), parseInt(hx.slice(2, 4), 16), parseInt(hx.slice(4, 6), 16)];
}
function buildPerm(): void {
const rand = randRef.current;
const p: number[] = [];
for (let i = 0; i < 256; i++) p.push(i);
for (let i2 = 255; i2 > 0; i2--) {
const k2 = Math.floor(rand() * (i2 + 1));
const tmp = p[i2]; p[i2] = p[k2]; p[k2] = tmp;
}
const perm = new Uint8Array(512);
for (let i3 = 0; i3 < 512; i3++) perm[i3] = p[i3 & 255];
permRef.current = perm;
}
function fade2(k: number): number { return k * k * (3 - 2 * k); }
function vnoise(x: number, y: number): number {
const perm = permRef.current;
const xi = Math.floor(x), yi = Math.floor(y);
const xf = x - xi, yf = y - yi;
const a2 = perm[(perm[xi & 255] + yi) & 255];
const b2 = perm[(perm[(xi + 1) & 255] + yi) & 255];
const c2 = perm[(perm[xi & 255] + yi + 1) & 255];
const d2 = perm[(perm[(xi + 1) & 255] + yi + 1) & 255];
const u = fade2(xf), v = fade2(yf);
return (a2 + (b2 - a2) * u + (c2 - a2) * v + (a2 - b2 - c2 + d2) * u * v) / 255;
}
function idx(x: number, y: number): number {
const fw = fwRef.current, fh = fhRef.current;
let xx = x % fw; if (xx < 0) xx += fw;
let yy = y % fh; if (yy < 0) yy += fh;
return (yy * fw + xx) | 0;
}
function clampIdx(x: number, y: number): number {
const fw = fwRef.current, fh = fhRef.current;
const xx = Math.max(0, Math.min(fw - 1, Math.round(x)));
const yy = Math.max(0, Math.min(fh - 1, Math.round(y)));
return yy * fw + xx;
}
function sense(x: number, y: number): number {
return trailRef.current[clampIdx(x, y)];
}
function initAgents(): void {
const rand = randRef.current;
const fw = fwRef.current, fh = fhRef.current;
const A = agentsRef.current;
const ax = new Float32Array(A), ay = new Float32Array(A), ah = new Float32Array(A);
const cx = fw / 2, cy = fh / 2, r = Math.min(fw, fh) * 0.15;
for (let i = 0; i < A; i++) {
const a = rand() * Math.PI * 2, rr = rand() * r;
ax[i] = cx + Math.cos(a) * rr;
ay[i] = cy + Math.sin(a) * rr;
ah[i] = rand() * Math.PI * 2;
}
axRef.current = ax; ayRef.current = ay; ahRef.current = ah;
}
function stepAgents(): void {
const rand = randRef.current;
const A = agentsRef.current;
const fw = fwRef.current, fh = fhRef.current;
const ax = axRef.current, ay = ayRef.current, ah = ahRef.current;
const trail = trailRef.current;
for (let i = 0; i < A; i++) {
const x = ax[i], y = ay[i];
let h = ah[i];
const sf = sense(x + Math.cos(h) * SENSOR_DIST, y + Math.sin(h) * SENSOR_DIST);
const sl = sense(x + Math.cos(h + SENSOR_ANGLE) * SENSOR_DIST, y + Math.sin(h + SENSOR_ANGLE) * SENSOR_DIST);
const sr = sense(x + Math.cos(h - SENSOR_ANGLE) * SENSOR_DIST, y + Math.sin(h - SENSOR_ANGLE) * SENSOR_DIST);
if (sf >= sl && sf >= sr) {
// 직진
} else if (sl > sr) {
h += TURN;
} else if (sr > sl) {
h -= TURN;
} else {
h += (rand() < 0.5 ? 1 : -1) * TURN;
}
h += (rand() - 0.5) * 0.14;
let nx = x + Math.cos(h) * STEP, ny = y + Math.sin(h) * STEP;
nx = ((nx % fw) + fw) % fw; ny = ((ny % fh) + fh) % fh;
ax[i] = nx; ay[i] = ny; ah[i] = h;
const ii = idx(Math.round(nx), Math.round(ny));
trail[ii] = Math.min(CAP, trail[ii] + DEPOSIT);
}
stepCountRef.current++;
}
function diffuseEvap(): void {
const fw = fwRef.current, fh = fhRef.current;
const trail = trailRef.current, trailB = trailBRef.current;
const dc = decayRef.current;
for (let y = 0; y < fh; y++) {
const ym = y === 0 ? fh - 1 : y - 1, yp = y === fh - 1 ? 0 : y + 1;
const rowY = y * fw, rowYm = ym * fw, rowYp = yp * fw;
for (let x = 0; x < fw; x++) {
const xm = x === 0 ? fw - 1 : x - 1, xp = x === fw - 1 ? 0 : x + 1;
const i = rowY + x;
const avg = (trail[rowY + xm] + trail[rowY + xp] + trail[rowYm + x] + trail[rowYp + x]) * 0.25;
trailB[i] = (trail[i] * (1 - DIFFUSE) + avg * DIFFUSE) * (1 - dc);
}
}
trailRef.current = trailB; trailBRef.current = trail;
}
function capture(): void {
const fw = fwRef.current, fh = fhRef.current;
const tmp = snapOldRef.current;
snapOldRef.current = snapNewRef.current;
let snapNew = tmp;
if (!snapNew) snapNew = new Float32Array(fw * fh);
snapNew.set(trailRef.current);
snapNewRef.current = snapNew;
captureCountRef.current++;
setN(String(captureCountRef.current));
const trail = trailRef.current;
for (let i = 0; i < trail.length; i++) trail[i] = 0;
stepCountRef.current = 0;
initAgents();
}
function render(t: number): void {
const ctx = ctxRef.current;
const col = colRef.current;
const img = imgRef.current;
if (!ctx || !col || !img) return;
const fw = fwRef.current, fh = fhRef.current;
const trail = trailRef.current;
const snapOld = snapOldRef.current;
const snapNew = snapNewRef.current;
const fadeT = fadeTRef.current;
let mix = 1;
if (fadeT >= 0) {
mix = (t - fadeT) / FADE;
if (mix > 1) mix = 1;
mix = mix * mix * (3 - 2 * mix);
}
const data = img.data;
for (let y = 0; y < fh; y++) {
for (let x = 0; x < fw; x++) {
const i = y * fw + x;
const j = i * 4;
let vOld = snapOld && snapOld.length === trail.length ? snapOld[i] / CAP : 0;
let vNew = snapNew ? snapNew[i] / CAP : 0;
if (vOld > 1) vOld = 1; if (vNew > 1) vNew = 1;
const v = vOld + (vNew - vOld) * mix;
const k = v * v * (3 - 2 * v);
let rr = col.floor[0] + (col.trail[0] - col.floor[0]) * k * 0.5;
let gg = col.floor[1] + (col.trail[1] - col.floor[1]) * k * 0.5;
let bb = col.floor[2] + (col.trail[2] - col.floor[2]) * k * 0.5;
let vGrow = trail[i] / CAP; if (vGrow > 1) vGrow = 1;
const kGrow = vGrow * vGrow * (3 - 2 * vGrow);
rr += (col.acct[0] - rr) * kGrow * 0.5;
gg += (col.acct[1] - gg) * kGrow * 0.5;
bb += (col.acct[2] - bb) * kGrow * 0.5;
const n1 = vnoise(x * 0.09, y * 0.09 + t * 0.9);
const n2 = vnoise(x * 0.03 + 40, y * 0.03 + t * 0.6);
const sh = (n1 - 0.5) * 30 + (n2 - 0.5) * 20;
rr += sh; gg += sh; bb += sh;
data[j] = rr; data[j + 1] = gg; data[j + 2] = bb; data[j + 3] = 255;
}
}
ctx.putImageData(img, 0, 0);
}
function fit(): void {
const field = fieldRef.current;
const cv = cvRef.current;
if (!field || !cv) return;
const r = field.getBoundingClientRect();
const W = Math.round(r.width), H = Math.round(r.height);
const fw = Math.max(96, Math.min(200, Math.round(W / 3)));
const fh = Math.max(52, Math.min(120, Math.round(H / 3)));
fwRef.current = fw; fhRef.current = fh;
cv.width = fw; cv.height = fh;
cv.style.width = "100%"; cv.style.height = "100%";
const ctx = cv.getContext("2d", { alpha: false });
if (!ctx) return;
ctxRef.current = ctx;
const img = ctx.createImageData(fw, fh);
imgRef.current = img;
trailRef.current = new Float32Array(fw * fh);
trailBRef.current = new Float32Array(fw * fh);
snapOldRef.current = null; snapNewRef.current = null;
stepCountRef.current = 0; captureCountRef.current = 0; fadeTRef.current = -1;
initAgents();
}
function stillFrame(): void {
for (let k = 0; k < growStepsRef.current; k++) { stepAgents(); diffuseEvap(); }
capture();
render(2.6);
}
let t0 = -1;
function frame(now: number): void {
if (t0 < 0) t0 = now;
const t = (now - t0) / 1000;
for (let i = 0; i < SUBSTEPS; i++) { stepAgents(); diffuseEvap(); }
if (stepCountRef.current >= growStepsRef.current) { capture(); fadeTRef.current = t; }
if (fadeTRef.current >= 0 && t - fadeTRef.current > FADE) fadeTRef.current = -1;
render(t);
rafRef.current = requestAnimationFrame(frame);
}
useEffect(() => {
const root = rootRef.current;
if (!root) return;
agentsRef.current = agents;
decayRef.current = decay;
growStepsRef.current = growSteps;
randRef.current = makePRNG(0x320a08);
colRef.current = {
floor: tokRGB(root, "--sm-floor"),
trail: tokRGB(root, "--sm-trail"),
acct: tokRGB(root, "--sm-acct"),
};
buildPerm();
fit();
function onResize(): void {
fit();
if (reduced()) stillFrame();
}
window.addEventListener("resize", onResize);
if (reduced()) {
stillFrame();
setStill(true);
} else {
t0 = -1;
rafRef.current = requestAnimationFrame(frame);
}
return () => {
window.removeEventListener("resize", onResize);
cancelAnimationFrame(rafRef.current);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [agents, decay, growSteps]);
const rootCls = still ? `${styles.root} ${styles.isStill}` : styles.root;
return (
<main className={styles.stage}>
<div className={rootCls} ref={rootRef} style={vars}>
<p className={styles.hint}>
<span>네트워크가 다 자란 순간의 캔버스를 정지 이미지로 굳혀 옅은 투명도로 깔면, 움직이지 않아도 손으로 그린 듯한 유기적 질감이 카드·섹션 배경이 됩니다</span>
</p>
<div className={styles.field} ref={fieldRef} role="application" aria-label={FIELD_LABEL} tabIndex={0}>
<canvas className={styles.cv} ref={cvRef}></canvas>
<div className={styles.veil} aria-hidden="true">
<div className={styles.card}>
<p className={styles.cardT}>Organic Section</p>
<p className={styles.cardS}>hand-drawn texture · slime network</p>
</div>
</div>
</div>
<div className={styles.bar}>
<span className={styles.meta}>
<b className={styles.val}>{n}</b>
<span> 캡처 · 정지 질감</span>
</span>
<span className={styles.metaDim}>canvas · ImageData · requestAnimationFrame</span>
</div>
</div>
</main>
);
}08 Organic texture panel — capturing one frame as a card background — Measured area 34.819% · moving frames 23/23Original by GODRICH · SCSS and React ship in the zip · Slime Mold Simulation, 9 Ways (No Library)
The post this demo lives in
Slime Mold Simulation, 9 Ways (No Library)No library, no WebGL — just thousands of dots sniffing front, left, right and turning toward the strongest scent, and a See all demos in this post
If you like this effect - similar demos
Creative UI02 Stripe bands — one parameter turns dots into lines9 Reaction Diffusion Simulations, No Library
Creative UI01 One sphere — the first 3D a minimal marcher makes9 Ray Marching Scenes in Canvas (No WebGL)
Creative UI09 Ecosystem scene — sand, water, fire and plants running together in one gridFalling Sand Simulator, 9 Ways (No Library)