08ASCII density — brightness choosing glyphs
Each grid cell's alpha is read as a density that picks one glyph from a preset character ladder stamped with fillText, and sliding the ladder over time changes the order the board fills in.
Best forRetro terminal and developer landings
fillTextgetImageDatarequestAnimationFrame
<main class="stage">
<div class="ga" id="ga">
<p class="ga__hint">
<svg class="ga__ico" viewBox="0 0 256 256" aria-hidden="true"><g fill="none" stroke="currentColor" stroke-width="12" stroke-linecap="round"><path d="M64 48h72M64 96h128M64 144h96M64 192h128" opacity=".9"/><path d="M40 48h8M40 96h8M40 144h8M40 192h8" opacity=".55"/></g></svg>
<span>Change the word and the character grid reassembles</span>
</p>
<div class="ga__field" id="field" role="application" aria-label="ASCII density playground" tabindex="0">
<canvas class="ga__cv" id="cv"></canvas>
<b class="ga__badge" aria-hidden="true" id="badge">0 pts</b>
</div>
<div class="ga__bar">
<label class="ga__dial">Word
<input type="text" id="word" value="ASCII" maxlength="12" spellcheck="false" aria-label="Word">
</label>
<label class="ga__dial">Seed
<input type="number" id="seed" min="1" max="9999" value="7" aria-label="Seed">
</label>
</div>
</div>
</main>@use "../../../../site/static/demo-tokens" as *;
// ASCII 밀도 — 움직임은 전부 캔버스 rAF 루프 안에 있다(@keyframes 0개 — 077-03 패턴).
// 글자색은 파스텔 변수를 커스텀 프로퍼티로 내려 JS 가 읽어 쓴다. 리터럴 hex 는 없다(BD26).
$glyph-ink: $subject-ink; // 글릿 본색 — 잉크
$glyph-sky: mix($subject-sky, $stage-paper, 42%); // 파스텔 하늘
$glyph-mint: mix($subject-mint, $stage-paper, 42%); // 파스텔 민트
$glyph-peach: mix($subject-orange-deep, $stage-paper, 30%); // 파스텔 복숭아
@include stage($stage-paper);
.ga {
--g0: #{$glyph-ink};
--g1: #{$glyph-sky};
--g2: #{$glyph-mint};
--g3: #{$glyph-peach};
display: flex; flex-direction: column; gap: $sp-2;
width: 100%; max-width: 424px;
}
.ga__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;
}
.ga__ico { width: 16px; height: 16px; flex: 0 0 auto; color: $glyph-ink; }
.ga__field {
position: relative; height: 180px;
border-radius: $r-card; overflow: hidden;
background: $stage-paper;
box-shadow: inset 0 0 0 1px rgba($subject-ink, .12);
}
.ga__field:focus-visible { outline: 2px solid $glyph-sky; outline-offset: 2px; }
.ga__cv { display: block; width: 100%; height: 100%; }
// 마스크 안 칸 수를 화면에 적는다 — 런타임 샘플링이 이 데모의 요점이다
.ga__badge {
position: absolute; right: $sp-2; top: $sp-2;
padding: $sp-1 $sp-2; border-radius: $r-pill;
background: rgba($subject-ink, .78);
color: $subject-cream; font-weight: 700; font-size: 11px;
}
.ga__bar { display: flex; align-items: flex-end; gap: $sp-3; }
.ga__dial {
display: flex; flex-direction: column; gap: $sp-1;
font-weight: 700; font-size: 11px; color: $subject-ink;
}
.ga__dial input {
width: 120px; margin: 0; padding: $sp-1 $sp-2;
border: 1px solid rgba($subject-ink, .2); border-radius: $r-sm;
background: $stage-paper; color: $subject-ink;
font-weight: 700; font-size: 12px;
}
.ga__dial input[type="number"] { width: 72px; }
.ga__dial input:focus-visible { outline: 2px solid $glyph-sky; outline-offset: 1px; }
@media (max-width: 340px) {
.ga { gap: $sp-1; }
.ga__field { height: 100px; }
.ga__badge { font-size: 10px; padding: 0 $sp-1; }
.ga__dial input { width: 88px; }
.ga__dial input[type="number"] { width: 56px; }
.ga__hint { font-size: 10px; }
}
// reduce — 루프가 아예 안 돈다. t=0 계단 포즈 한 장이 남는다.
@media (prefers-reduced-motion: reduce) {
.ga.is-still .ga__field { cursor: default !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);
}
.ga {
--g0: #17141a;
--g1: rgb(76.1176470588%, 90.9411764706%, 100%);
--g2: rgb(70.5176470588%, 92.9176470588%, 85.3411764706%);
--g3: rgb(93.6470588235%, 75.6470588235%, 70%);
display: flex;
flex-direction: column;
gap: 8px;
width: 100%;
max-width: 424px;
}
.ga__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;
}
.ga__ico {
width: 16px;
height: 16px;
flex: 0 0 auto;
color: #17141a;
}
.ga__field {
position: relative;
height: 180px;
border-radius: 16px;
overflow: hidden;
background: #ffffff;
box-shadow: inset 0 0 0 1px rgba(23, 20, 26, 0.12);
}
.ga__field:focus-visible {
outline: 2px solid rgb(76.1176470588%, 90.9411764706%, 100%);
outline-offset: 2px;
}
.ga__cv {
display: block;
width: 100%;
height: 100%;
}
.ga__badge {
position: absolute;
right: 8px;
top: 8px;
padding: 4px 8px;
border-radius: 999px;
background: rgba(23, 20, 26, 0.78);
color: #fff7e6;
font-weight: 700;
font-size: 11px;
}
.ga__bar {
display: flex;
align-items: flex-end;
gap: 12px;
}
.ga__dial {
display: flex;
flex-direction: column;
gap: 4px;
font-weight: 700;
font-size: 11px;
color: #17141a;
}
.ga__dial input {
width: 120px;
margin: 0;
padding: 4px 8px;
border: 1px solid rgba(23, 20, 26, 0.2);
border-radius: 8px;
background: #ffffff;
color: #17141a;
font-weight: 700;
font-size: 12px;
}
.ga__dial input[type=number] {
width: 72px;
}
.ga__dial input:focus-visible {
outline: 2px solid rgb(76.1176470588%, 90.9411764706%, 100%);
outline-offset: 1px;
}
@media (max-width: 340px) {
.ga {
gap: 4px;
}
.ga__field {
height: 100px;
}
.ga__badge {
font-size: 10px;
padding: 0 4px;
}
.ga__dial input {
width: 88px;
}
.ga__dial input[type=number] {
width: 56px;
}
.ga__hint {
font-size: 10px;
}
}
@media (prefers-reduced-motion: reduce) {
.ga.is-still .ga__field {
cursor: default !important;
}
}// ASCII 밀도 — 글자를 픽셀로 뜯어 밝기가 글자를 고르는 판으로 짠다.
// 1) 오프스크린 캔버스에 fillText 로 단어를 그려 getImageData 로 알파 마스크를 뽑는다
// 2) 격자 칸(CELL px) 안 알파를 평균해 밀도(0..1) 로 읽는다 — 칸마다 하나의 값
// 3) 밀도 → 문자 계단 " .:-=+*#%@" 에서 한 글자를 골라 fillText 로 찍는다.
// 계단 기준을 시간에 따라 밀면 같은 밀도가 다른 글자로 바뀌어 판 전체가 살아 움직인다.
// Seed(mulberry32) 가 칸마다 색·주사 위상을 정하므로 같은 시드는 같은 그림이 나온다.
var root = document.getElementById('ga');
var field = document.getElementById('field');
var cv = document.getElementById('cv');
var ctx = cv.getContext('2d');
var wordIn = document.getElementById('word');
var seedIn = document.getElementById('seed');
var badge = document.getElementById('badge');
var SW = 252, SH = 108; // 샘플 해상도 — 판 비율과 같다
var CELL = 5; // 격자 칸(px) — 칸이 작을수록 판이 조밀해진다
var LADDER = ' .:-=+*#%@'; // 밀도 계단 — 옅은 것부터 짙은 것 순서
var CYCLE = 0.30; // 계단 슬라이드 주기(초) — 프레임 사이 83ms 에 계단이 확 걸린다
var reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
var W = 0, H = 0;
var cells = [];
var t0 = 0, raf = 0;
// 색 — scss 가 파스텔 커스텀 프로퍼티(--g0..--g3)로 내려준 넉 색을 읽어 쓴다
var css = getComputedStyle(root);
function hexOf(name) {
var v = css.getPropertyValue(name).trim().replace('#', '');
if (v.length === 3) v = v.charAt(0) + v.charAt(0) + v.charAt(1) + v.charAt(1) + v.charAt(2) + v.charAt(2);
return '#' + v;
}
var cols = [hexOf('--g0'), hexOf('--g1'), hexOf('--g2'), hexOf('--g3')];
// 결정적 난수 — Seed 하나가 칸의 색·위상을 정한다
function mulberry32(a) {
return function () {
a |= 0; a = a + 0x6D2B79F5 | 0;
var t = Math.imul(a ^ a >>> 15, 1 | a);
t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
return ((t ^ t >>> 14) >>> 0) / 4294967296;
};
}
// ── 1) 글자 → 알파 마스크 ────────────────────────────────────────
function buildMask(word) {
var off = document.createElement('canvas');
off.width = SW; off.height = SH;
var oc = off.getContext('2d', { willReadFrequently: true });
oc.textAlign = 'center'; oc.textBaseline = 'middle';
var fs = 200;
oc.font = '900 ' + fs + 'px Arial';
var w = oc.measureText(word).width || 1;
fs = Math.min(fs * ((SW - 8) / w), SH - 6); // 폭·높이 안에서 제일 큰 글자
oc.font = '900 ' + Math.round(fs) + 'px Arial';
oc.fillStyle = '#fff';
oc.fillText(word, SW / 2, SH / 2);
return oc.getImageData(0, 0, SW, SH).data;
}
// ── 2) 마스크 → 칸 밀도 격자 ────────────────────────────────────
// 칸 안 픽셀 알파를 전부 더해 평균 — 두께·가장자리 반쯤 걸친 칸까지 값으로 읽는다
function buildCells(word) {
var data = buildMask(word);
var cw = Math.floor(SW / CELL), ch = Math.floor(SH / CELL);
var rnd = mulberry32(seed);
var out = [];
for (var cy = 0; cy < ch; cy++) {
for (var cx = 0; cx < cw; cx++) {
var sum = 0, n = 0;
for (var py = cy * CELL; py < (cy + 1) * CELL; py++) {
for (var px = cx * CELL; px < (cx + 1) * CELL; px++) {
sum += data[(py * SW + px) * 4 + 3]; n++;
}
}
var d = sum / (n * 255); // 0..1 밀도
var r1 = rnd(), r2 = rnd();
out.push({
cx: cx, cy: cy,
d: d,
ci: d > 0.02 ? (r1 < 0.6 ? 0 : r1 < 0.78 ? 1 : r1 < 0.9 ? 2 : 3) : 0,
ph: r2 * 6.2832 // 주사 위상 — 시드가 정한다
});
}
}
return out;
}
function pickColor(r) {
if (r < 0.55) return 0; // 잉크 다수
if (r < 0.73) return 1; // 하늘
if (r < 0.88) return 2; // 민트
return 3; // 복숭아
}
// ── 3) Word·시드가 바뀌면 칸 격자가 다시 계산된다 ─────────────────
var word = 'ASCII', seed = 7;
function resample(nextWord, nextSeed) {
var w = String(nextWord == null ? word : nextWord).trim().toUpperCase();
if (w) word = w; // 빈 문자열이면 직전 값을 유지
var s = Math.floor(Number(nextSeed));
if (s >= 1) seed = s;
cells = buildCells(word);
var inMask = 0;
for (var i = 0; i < cells.length; i++) if (cells[i].d > 0.02) inMask++;
window.__sampleInfo = { targets: inMask, particles: cells.length };
badge.textContent = inMask + ' pts';
if (reduce) {
paint(0); // t=0 계단 포즈 한 장
} else {
t0 = performance.now();
}
}
function fit() {
var r = field.getBoundingClientRect();
var d = window.devicePixelRatio || 1;
W = r.width; H = r.height;
cv.width = Math.round(W * d); cv.height = Math.round(H * d);
ctx.setTransform(d, 0, 0, d, 0, 0);
}
function paint(t) {
ctx.clearRect(0, 0, W, H);
var sx = W / SW, sy = H / SH;
var fs = CELL * 1.5 * sx; // 칸보다 반 큰 활자 — 판이 성기지 않게
ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
// 계단 슬라이드 — 밀도→글자 대응이 시간에 따라 밀린다(등장 시퀀스: 판이 차오르는 결).
// 슬라이드 항은 잠시 등장에만 쓰고(0.28 계수로 완만) 상시 운동은 아래 사인 주사가 맡는다
var slide = (t / CYCLE) * LADDER.length;
var bgA = 0.46 + 0.36 * Math.sin(t * 5.3 * 0.5 + 1.1); // 바탕 주사 — 마스크 밖 칸의 명멸 알파
// 바탕 계단 위치 — 주사 사인의 절반 위상으로 마스크 밖 칸이 0..2 계단을 오간다.
// 마스크 안(글릿)과 위상이 어긋나므로 두 층이 번갈아 살아 움직인다
var slBg = Math.sin(t * 5.3 + 2.2) * 5.0 - 0.6;
for (var i = 0; i < cells.length; i++) {
var c = cells[i];
var bg = c.d <= 0.02; // 마스크 밖 칸 — 바탕 주사가 담당
if (bg && slBg <= 0) continue; // 이 프레임에 바탕이 꺼져 있으면 쉰다
// 주사 위상 — 칸마다 Seed 위상으로 계단 슬라이드가 물린다. 위상이 퍼져 판 전체가 반짝인다.
// 진폭은 계단 전체 폭(LADDER.length) 을 넘게 — 마스크 안 모든 칸이 프레임마다
// 최소 한 계단 이상 오르내려 빈 칸(' ')과 짙은 글자를 오간다(면적 하선).
// 슬라이드 등장항은 사인 반주기(π/5.3≈0.59s) 안에 끝나도록 코사인 창으로 감쇠한다 —
// 창이 닫히면(≈1.2s 뒤) 순수 주사만 남아 2초 내내 계단이 계속 움직인다
var win = Math.max(0, Math.cos(Math.min(t * 2.6, Math.PI))); // 등장 창 — 1.2초 뒤 0
var sl = slide * 0.28 * win + Math.sin(t * 5.3 + c.ph) * (LADDER.length + 1.5) + Math.sin(t * 2.6 + c.ph * 2.7) * 2.2;
var lv = (bg ? 0 : c.d) * (LADDER.length - 1) + (bg ? slBg : sl);
var idx = Math.max(0, Math.min(LADDER.length - 1, Math.round(lv)));
var ch = LADDER.charAt(idx);
if (ch === ' ') continue; // 계단 아래로 떨어진 칸은 이 프레임에 쉰다
if (bg) ctx.globalAlpha = bgA; // 바탕 글자는 옅게 — 글릿보다 한 단계 뒤에 있다
ctx.fillStyle = cols[c.ci];
ctx.font = '700 ' + fs.toFixed(1) + 'px monospace';
ctx.fillText(ch, (c.cx + 0.5) * CELL * sx, (c.cy + 0.5) * CELL * sy);
if (bg) ctx.globalAlpha = 1;
}
}
function frame(now) {
paint((now - t0) / 1000);
raf = requestAnimationFrame(frame);
}
wordIn.addEventListener('input', function () { resample(wordIn.value, seedIn.value); });
seedIn.addEventListener('input', function () { resample(wordIn.value, seedIn.value); });
window.addEventListener('resize', function () { fit(); if (reduce) paint(0); });
fit();
resample(wordIn.value, seedIn.value);
if (reduce) {
root.classList.add('is-still'); // 루프 없이 t=0 한 장
} else {
raf = requestAnimationFrame(frame);
}// GlyphAsciiDensityMap — vanilla 판(run/310/demo/08-glyph-ascii-density-map/index.html) 의 React 포트.
// 오프스크린 캔버스에 fillText 로 단어를 그려 getImageData 로 알파 마스크를 뽑고,
// 격자 칸(CELL px) 안 알파를 평균해 밀도(0..1) 로 읽는다. 밀도 → 문자 계단 " .:-=+*#%@"
// 에서 한 글자를 골라 fillText 로 찍는다. 계단 기준을 시간에 따라 밀면 같은 밀도가 다른
// 글자로 바뀌어 판 전체가 살아 움직인다. 마스크 밖 칸은 바탕 주사가 옅게 명멸시켜
// 빈 화면까지 면적에 들어온다. 칸마다 색·주사 위상은 mulberry32(시드) 로 정한다.
// 움직임은 캔버스 rAF 루프가 전부 그리므로 @keyframes 는 없다 — props 는 CSS 변수로 내려간다.
import { useEffect, useRef, useState } from "react";
import type { CSSProperties } from "react";
import styles from "./GlyphAsciiDensityMap.module.scss";
export type GlyphAsciiDensityMapProps = {
duration?: string;
easing?: string;
color?: string;
};
type Vars = CSSProperties & { "--duration"?: string; "--easing"?: string; "--color"?: string };
type Box<T> = { current: T };
type InputEvt = { target: { value: string } };
const SW = 252, SH = 108; // 샘플 해상도 — 판 비율과 같다
const CELL = 5; // 격자 칸(px) — 칸이 작을수록 판이 조밀해진다
const LADDER = " .:-=+*#%@"; // 밀도 계단 — 옅은 것부터 짙은 것 순서
const CYCLE = 0.30; // 계단 슬라이드 주기(초) — 등장 시퀀스의 밀림 속도
const FIELD_LABEL = "ASCII 밀도 실험판";
// 결정적 난수 — mulberry32. 같은 시드면 같은 수열을 돌려준다
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 Cell = { cx: number; cy: number; d: number; ci: number; ph: number };
// 오프스크린 fillText → 알파 마스크 픽셀 배열
function buildMask(word: string): Uint8ClampedArray {
const off = document.createElement("canvas");
off.width = SW; off.height = SH;
const oc = off.getContext("2d", { willReadFrequently: true }) as CanvasRenderingContext2D;
oc.textAlign = "center"; oc.textBaseline = "middle";
let fs = 200;
oc.font = "900 " + fs + "px Arial";
const w = oc.measureText(word).width || 1;
fs = Math.min(fs * ((SW - 8) / w), SH - 6); // 폭·높이 안에서 제일 큰 글자
oc.font = "900 " + Math.round(fs) + "px Arial";
oc.fillStyle = "#fff";
oc.fillText(word, SW / 2, SH / 2);
return oc.getImageData(0, 0, SW, SH).data;
}
// 마스크 → 칸 밀도 격자. 칸 안 픽셀 알파를 전부 더해 평균 —
// 두께·가장자리 반쯤 걸친 칸까지 값으로 읽는다
function buildCells(word: string, seed: number): Cell[] {
const data = buildMask(word);
const cw = Math.floor(SW / CELL), ch = Math.floor(SH / CELL);
const rnd = mulberry32(seed);
const out: Cell[] = [];
for (let cy = 0; cy < ch; cy++) {
for (let cx = 0; cx < cw; cx++) {
let sum = 0, n = 0;
for (let py = cy * CELL; py < (cy + 1) * CELL; py++) {
for (let px = cx * CELL; px < (cx + 1) * CELL; px++) {
sum += data[(py * SW + px) * 4 + 3]; n++;
}
}
const d = sum / (n * 255); // 0..1 밀도
const r1 = rnd(), r2 = rnd();
out.push({
cx, cy, d,
ci: d > 0.02 ? (r1 < 0.6 ? 0 : r1 < 0.78 ? 1 : r1 < 0.9 ? 2 : 3) : 0,
ph: r2 * 6.2832, // 주사 위상 — 시드가 정한다
});
}
}
return out;
}
export default function GlyphAsciiDensityMap({
duration = "2s", // vanilla $duration: $dur-loop
easing = "cubic-bezier(.2, .8, .2, 1)", // vanilla $easing: $ease-spring
color = "#17141a", // vanilla $glyph-ink
}: GlyphAsciiDensityMapProps) {
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 cellsRef = useRef<Cell[]>([]) as Box<Cell[]>;
const colsRef = useRef<string[]>([]) as Box<string[]>;
const sizeRef = useRef({ w: 0, h: 0 }) as Box<{ w: number; h: number }>;
const stateRef = useRef({ word: "ASCII", seed: 7, t0: 0 }) as Box<{ word: string; seed: number; t0: number }>;
const rafRef = useRef(0) as Box<number>;
const [count, setCount] = 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 hex3to6(v: string): string {
if (v.length === 3) return v.charAt(0) + v.charAt(0) + v.charAt(1) + v.charAt(1) + v.charAt(2) + v.charAt(2);
return v;
}
function colors(): string[] {
const root = rootRef.current;
if (!root) return ["#17141a", "#17141a", "#17141a", "#17141a"];
const one = (n: string) => hex3to6(getComputedStyle(root).getPropertyValue(n).trim());
return [one("--g0"), one("--g1"), one("--g2"), one("--g3")];
}
// 고DPI 대응 — 배킹 스토어는 devicePixelRatio 배, 그리기 좌표계는 CSS 픽셀 그대로
function fit(): void {
const field = fieldRef.current;
const 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);
}
function paint(t: number): void {
const ctx = ctxRef.current;
const cells = cellsRef.current;
const cols = colsRef.current;
if (!ctx) return;
const W = sizeRef.current.w, H = sizeRef.current.h;
ctx.clearRect(0, 0, W, H);
const sx = W / SW, sy = H / SH;
const fs = CELL * 1.5 * sx; // 칸보다 반 큰 활자 — 판이 성기지 않게
ctx.textAlign = "center"; ctx.textBaseline = "middle";
// 계단 슬라이드 — 밀도→글자 대응이 시간에 따라 밀린다(등장 시퀀스: 판이 차오르는 결).
// 슬라이드 항은 잠시 등장에만 쓰고(0.28 계수로 완만) 상시 운동은 사인 주사가 맡는다
const slide = (t / CYCLE) * LADDER.length;
const bgA = 0.46 + 0.36 * Math.sin(t * 5.3 * 0.5 + 1.1); // 바탕 주사 — 마스크 밖 칸의 명멸 알파
// 바탕 계단 위치 — 주사 사인의 절반 위상으로 마스크 밖 칸이 0..2 계단을 오간다
const slBg = Math.sin(t * 5.3 + 2.2) * 5.0 - 0.6;
for (let i = 0; i < cells.length; i++) {
const c = cells[i];
const bg = c.d <= 0.02; // 마스크 밖 칸 — 바탕 주사가 담당
if (bg && slBg <= 0) continue; // 이 프레임에 바탕이 꺼져 있으면 쉰다
// 주사 위상 — 칸마다 시드 위상으로 계단 슬라이드가 물린다. 진폭은 계단 전체 폭을
// 넘게 — 마스크 안 모든 칸이 프레임마다 최소 한 계단 이상 오르내린다(면적 하선).
// 슬라이드 등장항은 사인 반주기 안에 끝나도록 코사인 창으로 감쇠한다(≈1.2s 뒤 0)
const win = Math.max(0, Math.cos(Math.min(t * 2.6, Math.PI))); // 등장 창
const sl = slide * 0.28 * win + Math.sin(t * 5.3 + c.ph) * (LADDER.length + 1.5) + Math.sin(t * 2.6 + c.ph * 2.7) * 2.2;
const lv = (bg ? 0 : c.d) * (LADDER.length - 1) + (bg ? slBg : sl);
const idx = Math.max(0, Math.min(LADDER.length - 1, Math.round(lv)));
const ch = LADDER.charAt(idx);
if (ch === " ") continue; // 계단 아래로 떨어진 칸은 이 프레임에 쉰다
if (bg) ctx.globalAlpha = bgA; // 바탕 글자는 옅게 — 글릿보다 한 단계 뒤에
ctx.fillStyle = cols[c.ci] || "#17141a";
ctx.font = "700 " + fs.toFixed(1) + "px monospace";
ctx.fillText(ch, (c.cx + 0.5) * CELL * sx, (c.cy + 0.5) * CELL * sy);
if (bg) ctx.globalAlpha = 1;
}
}
// 단어·시드가 바뀌면 칸 격자가 다시 계산된다(런타임 샘플링)
function resample(nextWord: string, nextSeed: number): void {
const st = stateRef.current;
const w = String(nextWord == null ? st.word : nextWord).trim().toUpperCase();
if (w) st.word = w;
if (nextSeed >= 1) st.seed = Math.floor(nextSeed);
cellsRef.current = buildCells(st.word, st.seed);
let inMask = 0;
for (let i = 0; i < cellsRef.current.length; i++) if (cellsRef.current[i].d > 0.02) inMask++;
setCount(inMask);
if (reduced()) {
paint(0); // t=0 계단 포즈 한 장
} else {
st.t0 = performance.now();
}
}
function frame(now: number): void {
paint((now - stateRef.current.t0) / 1000);
rafRef.current = requestAnimationFrame(frame);
}
function onWord(e: InputEvt): void {
resample(e.target.value, stateRef.current.seed);
}
function onSeed(e: InputEvt): void {
const v = Math.floor(Number(e.target.value)) || 1;
resample(stateRef.current.word, v);
}
function onResize(): void {
fit();
if (reduced()) paint(0);
}
useEffect(() => {
const cv = cvRef.current;
if (!cv) return;
ctxRef.current = cv.getContext("2d");
if (!ctxRef.current) return;
colsRef.current = colors();
fit();
resample("ASCII", 7);
window.addEventListener("resize", onResize);
if (reduced()) {
setStill(true);
} else {
rafRef.current = requestAnimationFrame(frame);
}
return () => {
window.removeEventListener("resize", onResize);
cancelAnimationFrame(rafRef.current);
};
}, []);
const cls = [styles.root, still ? 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="none" stroke="currentColor" stroke-width="12" stroke-linecap="round"><path d="M64 48h72M64 96h128M64 144h96M64 192h128" opacity=".9"/><path d="M40 48h8M40 96h8M40 144h8M40 192h8" opacity=".55"/></g></svg>
<span>단어를 바꾸면 글자판이 다시 짜입니다</span>
</p>
<div className={styles.field} ref={fieldRef} role="application" aria-label={FIELD_LABEL} tabIndex={0}>
<canvas className={styles.cv} ref={cvRef} id="cv"></canvas>
<b className={styles.badge} aria-hidden="true">{count} pts</b>
</div>
<div className={styles.bar}>
<label className={styles.dial}>단어
<input type="text" id="word" defaultValue="ASCII" maxLength={12} spellCheck={false} aria-label="단어" onInput={onWord} />
</label>
<label className={styles.dial}>시드
<input type="number" id="seed" defaultValue={7} min={1} max={9999} aria-label="시드" onInput={onSeed} />
</label>
</div>
</div>
</main>
);
}08 ASCII density — brightness choosing glyphs — Measured area 32.283% · moving frames 23/23Original by GODRICH · SCSS and React ship in the zip · 9 Text Particle Effect CSS Ideas From Pixels
The post this demo lives in
If you like this effect - similar demos
Creative UI05 Thread portrait — brightness rewritten as thread densityString Art: 9 Thread-Geometry Demos
Creative UI09 A flock that spells — a sentence assembling while dodging the pointer9 Canvas Boids Algorithm Flocking Birds Simulation
Creative UI07 Contour bands — stacking thresholds into a topographic map9 Metaball Effect Scenes, Marching Squares Canvas