07Isometric 3D Columns Whose Top and Sides Shade by Light Direction
It raises a column in each grid cell with an isometric projection at ISO_ANGLE_DEG to get the top and two side faces, sets each face's brightness from the dot product of its normal and a LIGHT_AZIMUTH_DEG light vector, draws back cells first for correct overlap, and keeps column depth at DEPTH_PX.
Best forA hero showing regional figures in 3D
ISO_ANGLE_DEGLIGHT_AZIMUTH_DEGDEPTH_PX

<main class="stage">
<div class="bc is-demo" id="bc">
<canvas class="bc__canvas" data-role="canvas" width="480" height="300" tabindex="0" aria-label="An isometric 3D column chart whose top and side brightness change with the light direction. Move the light with the pointer and pick a column with ←/→ to hear its name and value"></canvas>
<p class="bc__status" data-role="status" aria-live="off">Pick a column with ←/→</p>
<div class="bc__tools">
<button class="bc__btn" data-role="spin" type="button" aria-pressed="false">Stop light</button>
<button class="bc__btn" data-role="data" type="button">New data</button>
</div>
</div>
</main>@use "../../../../site/static/demo-tokens" as *;
@include stage($stage-ink);
.bc {
position: relative;
width: min(92vw, calc(160vh - 12.8vw));
aspect-ratio: 480 / 300;
margin: 0 auto;
border-radius: $r-card;
overflow: hidden;
box-shadow: $shadow-raised;
background: $subject-ink;
}
.bc__canvas {
display: block;
width: 100%;
height: 100%;
cursor: crosshair;
}
.bc__canvas:focus-visible {
outline: 2px solid rgba(255, 255, 255, .85);
outline-offset: -6px;
}
.bc__status {
position: absolute;
right: $sp-3;
top: $sp-3;
box-sizing: border-box;
max-width: 46%;
margin: 0;
text-align: right;
padding: $sp-1 $sp-3;
border-radius: $r-control;
background: rgba(255, 255, 255, .85);
color: $subject-ink;
font-weight: 500;
font-size: 11px;
line-height: 1.4;
pointer-events: none;
}
// 그래프는 아래쪽 판에 있다 — 버튼은 왼쪽 위, 상태 줄은 오른쪽 위 띠에 두어 막대를 덮지 않는다
.bc__tools {
position: absolute;
left: $sp-3;
top: $sp-3;
box-sizing: border-box;
max-width: 50%;
display: flex;
flex-wrap: wrap;
gap: $sp-2;
}
.bc__btn {
margin: 0;
padding: $sp-1 $sp-3;
border: 0;
border-radius: $r-pill;
background: rgba(255, 255, 255, .85);
color: $subject-ink;
font: inherit;
font-weight: 500;
font-size: 12px;
line-height: 1.4;
cursor: pointer;
transition: background-color $dur-quick ease-out;
}
.bc__btn:hover {
background: $subject-cream;
}
.bc__btn[aria-pressed="true"] {
background: $subject-mint;
}
.bc__btn:focus-visible {
outline: 2px solid rgba(255, 255, 255, .95);
outline-offset: 2px;
}
// 손가락 가로 끌기는 이 캔버스가 받고, 세로 쓸기는 브라우저에 남겨 페이지 스크롤이 막히지 않게 한다
.bc__canvas { touch-action: pan-y; }
@media (max-width: 340px) {
.bc__btn { font-size: 10px; padding: $sp-1 $sp-2; }
.bc__status { font-size: 10px; padding: $sp-1 $sp-2; }
}
@media (prefers-reduced-motion: reduce) {
.bc__btn { transition: none; }
}html, body {
margin: 0;
overflow: hidden;
}
.stage {
box-sizing: border-box;
min-height: 100vh;
display: grid;
place-items: center;
margin: 0;
background: #17141a;
font-family: -apple-system, "Segoe UI", "Noto Sans KR", sans-serif;
padding: clamp(8px, 4vw, 24px);
}
.bc {
position: relative;
width: min(92vw, 160vh - 12.8vw);
aspect-ratio: 480/300;
margin: 0 auto;
border-radius: 16px;
overflow: hidden;
box-shadow: 0 14px 24px rgba(23, 20, 26, 0.32);
background: #17141a;
}
.bc__canvas {
display: block;
width: 100%;
height: 100%;
cursor: crosshair;
}
.bc__canvas:focus-visible {
outline: 2px solid rgba(255, 255, 255, 0.85);
outline-offset: -6px;
}
.bc__status {
position: absolute;
right: 12px;
top: 12px;
box-sizing: border-box;
max-width: 46%;
margin: 0;
text-align: right;
padding: 4px 12px;
border-radius: 12px;
background: rgba(255, 255, 255, 0.85);
color: #17141a;
font-weight: 500;
font-size: 11px;
line-height: 1.4;
pointer-events: none;
}
.bc__tools {
position: absolute;
left: 12px;
top: 12px;
box-sizing: border-box;
max-width: 50%;
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.bc__btn {
margin: 0;
padding: 4px 12px;
border: 0;
border-radius: 999px;
background: rgba(255, 255, 255, 0.85);
color: #17141a;
font: inherit;
font-weight: 500;
font-size: 12px;
line-height: 1.4;
cursor: pointer;
transition: background-color 220ms ease-out;
}
.bc__btn:hover {
background: #fff7e6;
}
.bc__btn[aria-pressed=true] {
background: #4cd4a6;
}
.bc__btn:focus-visible {
outline: 2px solid rgba(255, 255, 255, 0.95);
outline-offset: 2px;
}
.bc__canvas {
touch-action: pan-y;
}
@media (max-width: 340px) {
.bc__btn {
font-size: 10px;
padding: 4px 8px;
}
.bc__status {
font-size: 10px;
padding: 4px 8px;
}
}
@media (prefers-reduced-motion: reduce) {
.bc__btn {
transition: none;
}
}(function () {
const root = document.getElementById("bc");
if (!root) return;
const W = 480;
const H = 300;
const FIXED_DT = 16;
const TAU = Math.PI * 2;
// 파스텔 팔레트 — 어두운 무대 위에 밝은 막대를 얹어 명도 차로 경계가 읽힌다
const BG = [24, 26, 38];
const PANEL = [36, 39, 56];
const PAPER = [250, 246, 236];
const INK = [30, 30, 44];
const PAL = [
[126, 190, 255],
[255, 164, 190],
[130, 224, 190],
[192, 168, 255],
[255, 206, 160],
[244, 226, 140],
[150, 220, 236],
[230, 184, 226],
[196, 220, 160],
[176, 196, 236],
];
// 가상 데이터의 이름 — 실제 항목이 아니라 순서만 뜻한다
const LABELS = ['Item A', 'Item B', 'Item C', 'Item D', 'Item E', 'Item F', 'Item G', 'Item H', 'Item I', 'Item J'];
function clamp(v, lo, hi) { return v < lo ? lo : (v > hi ? hi : v); }
function lerp(a, b, k) { return a + (b - a) * k; }
function smooth(x) { const c = clamp(x, 0, 1); return c * c * (3 - 2 * c); }
function rgba(c, a) {
return 'rgba(' + Math.round(c[0]) + ',' + Math.round(c[1]) + ',' + Math.round(c[2]) + ',' + clamp(a, 0, 1).toFixed(3) + ')';
}
function mix(a, b, k) { return [lerp(a[0], b[0], k), lerp(a[1], b[1], k), lerp(a[2], b[2], k)]; }
const canvasEl = root.querySelector('[data-role="canvas"]');
const statusEl = root.querySelector('[data-role="status"]');
const ctxRaw = canvasEl ? canvasEl.getContext('2d') : null;
if (!canvasEl || !ctxRaw || !statusEl) {
return;
}
const cv = canvasEl;
const ctx = ctxRaw;
const status = statusEl;
const reduceQuery = window.matchMedia('(prefers-reduced-motion: reduce)');
// 움직임 줄이기 — 열린 페이지에서 설정을 바꿔도 아래 tail 의 change 리스너가 이 값을 다시 읽는다
let still = reduceQuery.matches;
// 자동 시연 중인가 — 사람이 처음 만지는 순간 시연을 멈추고 상태 줄을 읽어 주기 시작한다
let demo = root.classList.contains('is-demo');
function wake() {
if (!demo) {
return;
}
demo = false;
root.classList.remove('is-demo');
status.setAttribute('aria-live', 'polite');
}
function say(text) {
if (status.textContent !== text) {
status.textContent = text;
}
}
function fitCanvas() {
// 배율은 2 에서 자른다 — 배율 3 기기에서 화소가 2.25배로 늘어 프레임마다 일이 그만큼 커지지 않게
const dpr = Math.min(window.devicePixelRatio || 1, 2);
cv.width = Math.round(W * dpr);
cv.height = Math.round(H * dpr);
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
}
function onResize() {
fitCanvas();
draw();
}
fitCanvas();
window.addEventListener('resize', onResize);
// 화면 좌표(CSS px) → 장면 좌표(480x300). 리사이즈 뒤에도 늘 현재 크기로 다시 잰다
function toScene(ev) {
const r = cv.getBoundingClientRect();
return [((ev.clientX - r.left) / r.width) * W, ((ev.clientY - r.top) / r.height) * H];
}
// 시드 고정 난수 — 같은 시드면 같은 가상 데이터가 다시 나온다 (32비트 정수 섞기)
function makeRng(seed) {
let s = seed >>> 0;
return function () {
s = (s + 0x6d2b79f5) >>> 0;
let t = s;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function seededValues(seed, n, lo, hi) {
const rnd = makeRng(seed);
const out = [];
for (let i = 0; i < n; i += 1) {
out.push(lo + Math.floor(rnd() * (hi - lo + 1)));
}
return out;
}
// 세 자리마다 쉼표 — 지역 설정에 기대지 않는다
function groupDigits(n) {
const s = String(Math.round(Math.abs(n)));
let out = '';
for (let i = 0; i < s.length; i += 1) {
if (i > 0 && (s.length - i) % 3 === 0) {
out += ',';
}
out += s[i];
}
return (n < 0 ? '-' : '') + out;
}
// 세로 막대 경로 — 기준선 base 에서 h 만큼(음수면 아래로) 뻗고, 끝 모서리만 둥글린다
function barPath(c, x, base, w, h, r) {
const rr = Math.min(r, Math.abs(h), w / 2);
const tip = base - h;
const s = h >= 0 ? 1 : -1;
c.beginPath();
c.moveTo(x, base);
c.lineTo(x, tip + s * rr);
c.quadraticCurveTo(x, tip, x + rr, tip);
c.lineTo(x + w - rr, tip);
c.quadraticCurveTo(x + w, tip, x + w, tip + s * rr);
c.lineTo(x + w, base);
c.closePath();
}
// 가로 막대 경로 — 왼쪽 x0 에서 len 만큼 뻗고 오른쪽 끝만 둥글린다
function hbarPath(c, x0, y, len, th, r) {
const rr = Math.min(r, Math.max(len, 0), th / 2);
const x1 = x0 + Math.max(len, 0);
c.beginPath();
c.moveTo(x0, y);
c.lineTo(x1 - rr, y);
c.quadraticCurveTo(x1, y, x1, y + rr);
c.lineTo(x1, y + th - rr);
c.quadraticCurveTo(x1, y + th, x1 - rr, y + th);
c.lineTo(x0, y + th);
c.closePath();
}
function clearStage() {
ctx.fillStyle = rgba(BG, 1);
ctx.fillRect(0, 0, W, H);
}
function axisText(text, x, y, align, a) {
ctx.font = '500 10px sans-serif';
ctx.textAlign = align;
ctx.textBaseline = 'middle';
ctx.fillStyle = rgba(PAPER, a);
ctx.fillText(text, x, y);
}
// 고른 막대 — 화살표 키·포인터가 가리키는 sel 과 Enter·Space·클릭으로 고정한 pinned
let sel = -1;
let pinned = -1;
function focusIdx() { return sel >= 0 ? sel : pinned; }
function nextIdx(cur, d, n) {
return cur < 0 ? (d > 0 ? 0 : n - 1) : (cur + d + n) % n;
}
function togglePin(i) {
pinned = i < 0 || pinned === i ? -1 : i;
}
// 고른 막대 테두리 — 화살표·포인터로 가리키기만 하면 점선, Enter·Space·클릭으로 고정하면 실선
function ringStyle(i, a) {
ctx.strokeStyle = rgba(PAPER, 0.95 * a);
ctx.lineWidth = 2;
ctx.setLineDash(i === pinned ? [] : [4, 3]);
}
// 키보드 — ←/→ 막대 옮기기, Enter·Space 고르기, Esc 풀기. 셋 다 상태 줄이 이름과 값을 읽는다
function bindKeys(move, changed) {
cv.addEventListener('keydown', function (ev) {
if (ev.key === 'ArrowRight' || ev.key === 'ArrowLeft') {
ev.preventDefault();
wake();
move(ev.key === 'ArrowRight' ? 1 : -1);
changed();
}
else if (ev.key === 'Enter' || ev.key === ' ') {
ev.preventDefault();
wake();
togglePin(focusIdx());
changed();
}
else if (ev.key === 'Escape') {
ev.preventDefault();
wake();
sel = -1;
pinned = -1;
changed();
}
});
}
// 포인터 — 올리면 sel, 누르면 그 막대를 고정(같은 막대를 다시 누르면 풀기)
function bindPointer(hit, changed) {
cv.addEventListener('pointermove', function (ev) {
if (demo) {
return;
}
const p = toScene(ev);
const i = hit(p[0], p[1]);
if (i !== sel) {
sel = i;
changed();
}
});
cv.addEventListener('pointerdown', function (ev) {
wake();
const p = toScene(ev);
const i = hit(p[0], p[1]);
sel = i;
togglePin(i);
changed();
});
}
// 시연 일정 — 루프 안의 시각(ms) 표를 지날 때마다 한 번씩 부른다
let schedCycle = -1;
let schedIdx = 0;
function runSchedule(t, loop, marks, fire) {
const cyc = Math.floor(t / loop);
const p = t - cyc * loop;
if (cyc !== schedCycle) {
schedCycle = cyc;
schedIdx = 0;
}
while (schedIdx < marks.length && p >= marks[schedIdx]) {
fire(schedIdx, cyc);
schedIdx += 1;
}
}
// 등축 투영 각 — 바닥의 x·y 축이 화면 가로에서 이 각만큼 기운다 (cos 는 가로, sin 은 세로 몫)
const ISO_ANGLE_DEG = 30;
// 빛이 오는 방향 — 바닥 평면에서 +x 축을 0° 로 잰 방위각. 시연·포인터가 이 값에서 출발해 돌린다
const LIGHT_AZIMUTH_DEG = 135;
// 기둥 바닥의 한 변(px) — 칸 CELL 보다 작아 기둥 사이에 길이 생긴다
const DEPTH_PX = 24;
const LIGHT_ELEV_DEG = 42;
const AMBIENT = 0.3;
const GRID = 4;
const CELL = 34;
const SEED = 4707;
const OX = 240;
const OY = 134;
const HEIGHT_LERP = 0.12;
const SPIN_DEG_PER_S = 180;
const DEMO_LOOP = 2000;
const ROWS = ['A', 'B', 'C', 'D'];
const TXT_IDLE = 'Pick a column with ←/→';
const spinBtn = root.querySelector('[data-role="spin"]');
const dataBtn = root.querySelector('[data-role="data"]');
const DEG = Math.PI / 180;
const cosA = Math.cos(ISO_ANGLE_DEG * DEG);
const sinA = Math.sin(ISO_ANGLE_DEG * DEG);
const N = GRID * GRID;
let seed = SEED;
let goal = seededValues(seed, N, 18, 100);
const hgt = goal.map(function () { return 0; });
let azimuth = LIGHT_AZIMUTH_DEG;
let spinning = true;
let aiming = false;
// 등축 투영 — 바닥 (wx, wy) 와 높이 wz 를 화면 점으로
function project(wx, wy, wz) {
return [OX + (wx - wy) * cosA, OY + (wx + wy) * sinA - wz];
}
// 빛 벡터 — 방위각과 고도에서 단위 벡터 (Lx, Ly, Lz)
function lightVec() {
const az = azimuth * DEG;
const el = LIGHT_ELEV_DEG * DEG;
return [Math.cos(el) * Math.cos(az), Math.cos(el) * Math.sin(az), Math.sin(el)];
}
// 면 밝기 — 바탕 빛 AMBIENT 에 법선·빛 내적(음수면 0)을 더한다
function shade(nx, ny, nz, L) {
return AMBIENT + (1 - AMBIENT) * Math.max(0, nx * L[0] + ny * L[1] + nz * L[2]);
}
function tone(c, b) { return [clamp(c[0] * b, 0, 255), clamp(c[1] * b, 0, 255), clamp(c[2] * b, 0, 255)]; }
function poly(pts) {
ctx.beginPath();
ctx.moveTo(pts[0][0], pts[0][1]);
for (let i = 1; i < pts.length; i += 1) {
ctx.lineTo(pts[i][0], pts[i][1]);
}
ctx.closePath();
}
// 볼록 껍질 — 바닥 네 점과 그림자로 옮긴 네 점을 한 덩어리 그림자로 감싼다
function hull(ps) {
const p = ps.slice().sort(function (a, b) { return a[0] - b[0] || a[1] - b[1]; });
const cross = function (o, a, b) { return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]); };
const lo = [];
for (let i = 0; i < p.length; i += 1) {
while (lo.length >= 2 && cross(lo[lo.length - 2], lo[lo.length - 1], p[i]) <= 0) {
lo.pop();
}
lo.push(p[i]);
}
const up = [];
for (let i = p.length - 1; i >= 0; i -= 1) {
while (up.length >= 2 && cross(up[up.length - 2], up[up.length - 1], p[i]) <= 0) {
up.pop();
}
up.push(p[i]);
}
lo.pop();
up.pop();
return lo.concat(up);
}
function cellOf(i) {
const gx = i % GRID;
const gy = Math.floor(i / GRID);
const x0 = gx * CELL + (CELL - DEPTH_PX) / 2;
const y0 = gy * CELL + (CELL - DEPTH_PX) / 2;
return [x0, y0, x0 + DEPTH_PX, y0 + DEPTH_PX];
}
function step() {
for (let i = 0; i < N; i += 1) {
hgt[i] += (goal[i] - hgt[i]) * HEIGHT_LERP;
}
if (spinning && !aiming) {
azimuth = (azimuth + SPIN_DEG_PER_S * FIXED_DT / 1000) % 360;
}
}
function settle() {
for (let i = 0; i < N; i += 1) {
hgt[i] = goal[i];
}
}
function nameOf(i) { return ROWS[Math.floor(i / GRID)] + String((i % GRID) + 1); }
function report() {
const f = focusIdx();
if (f >= 0) {
say(nameOf(f) + ' · ' + groupDigits(goal[f]));
}
else {
say(TXT_IDLE);
}
}
function demoTick(t) {
// 시연 — 빛이 한 바퀴 반을 돌고, 루프 처음에 기둥이 바닥에서 솟는다
runSchedule(t, DEMO_LOOP, [200], function () {
for (let i = 0; i < N; i += 1) {
hgt[i] = 0;
}
});
}
function draw() {
clearStage();
const L = lightVec();
const ext = GRID * CELL;
// 바닥 판
ctx.fillStyle = rgba(PANEL, 1);
poly([project(0, 0, 0), project(ext, 0, 0), project(ext, ext, 0), project(0, ext, 0)]);
ctx.fill();
// 그림자 — 높이 h 인 꼭대기를 빛 반대쪽으로 h·(Lx, Ly)/Lz 만큼 바닥에 눕힌다
ctx.fillStyle = 'rgba(6,6,14,0.38)';
for (let i = 0; i < N; i += 1) {
const c = cellOf(i);
const h = hgt[i];
const sx = -h * L[0] / L[2];
const sy = -h * L[1] / L[2];
const base = [[c[0], c[1]], [c[2], c[1]], [c[2], c[3]], [c[0], c[3]]];
const pts = [];
for (let k = 0; k < 4; k += 1) {
pts.push(base[k]);
pts.push([base[k][0] + sx, base[k][1] + sy]);
}
poly(hull(pts).map(function (q) { return project(clamp(q[0], 0, ext), clamp(q[1], 0, ext), 0); }));
ctx.fill();
}
// 뒤에서 앞으로 — gx + gy 가 작은 칸(화면 위쪽)부터 그려 앞 기둥이 뒤 기둥을 가린다
const order = [];
for (let i = 0; i < N; i += 1) {
order.push(i);
}
order.sort(function (a, b) { return (a % GRID + Math.floor(a / GRID)) - (b % GRID + Math.floor(b / GRID)); });
const f = focusIdx();
const bTop = shade(0, 0, 1, L);
const bRight = shade(1, 0, 0, L);
const bLeft = shade(0, 1, 0, L);
for (let n = 0; n < N; n += 1) {
const i = order[n];
const c = cellOf(i);
const z = hgt[i] + (i === f ? 6 : 0);
const col = PAL[(i % GRID + Math.floor(i / GRID)) % PAL.length];
const dim = f >= 0 && f !== i ? 0.6 : 1;
// +y 쪽 면(화면 왼쪽 아래)
ctx.fillStyle = rgba(tone(col, bLeft * 1.1), dim);
poly([project(c[0], c[3], 0), project(c[2], c[3], 0), project(c[2], c[3], z), project(c[0], c[3], z)]);
ctx.fill();
// +x 쪽 면(화면 오른쪽 아래)
ctx.fillStyle = rgba(tone(col, bRight * 1.1), dim);
poly([project(c[2], c[1], 0), project(c[2], c[3], 0), project(c[2], c[3], z), project(c[2], c[1], z)]);
ctx.fill();
// 윗면
ctx.fillStyle = rgba(tone(col, bTop * 1.1), dim);
poly([project(c[0], c[1], z), project(c[2], c[1], z), project(c[2], c[3], z), project(c[0], c[3], z)]);
ctx.fill();
if (i === f) {
ringStyle(i, 1);
ctx.stroke();
ctx.setLineDash([]);
const tp = project((c[0] + c[2]) / 2, (c[1] + c[3]) / 2, z);
ctx.font = '700 11px sans-serif';
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
ctx.fillStyle = rgba(PAPER, 0.95);
ctx.fillText(nameOf(i) + ' ' + groupDigits(goal[i]), tp[0], tp[1] - 6);
}
}
// 빛 나침반 — 오른쪽 아래, 바닥 평면에서 빛이 오는 쪽을 가리킨다
const cx = 428;
const cy = 252;
const tip = project(Math.cos(azimuth * DEG) * 22, Math.sin(azimuth * DEG) * 22, 0);
const org = project(0, 0, 0);
ctx.strokeStyle = rgba(PAPER, 0.25);
ctx.lineWidth = 1;
ctx.beginPath();
ctx.ellipse(cx, cy, 22 * cosA * 1.41, 22 * sinA * 1.41, 0, 0, TAU);
ctx.stroke();
ctx.fillStyle = rgba(PAL[5], 1);
ctx.beginPath();
ctx.arc(cx + tip[0] - org[0], cy + tip[1] - org[1], 4, 0, TAU);
ctx.fill();
axisText(Math.round(azimuth) + '°', cx, cy, 'center', 0.7);
}
function after() {
if (still) {
settle();
}
report();
draw();
if (spinBtn) {
spinBtn.setAttribute('aria-pressed', spinning ? 'false' : 'true');
}
}
function inside(pt, pts) {
let hit = false;
for (let i = 0, j = pts.length - 1; i < pts.length; j = i, i += 1) {
const a = pts[i];
const b = pts[j];
if ((a[1] > pt[1]) !== (b[1] > pt[1]) && pt[0] < (b[0] - a[0]) * (pt[1] - a[1]) / (b[1] - a[1]) + a[0]) {
hit = !hit;
}
}
return hit;
}
// 포인터 자리의 기둥 — 앞 칸부터 윗면·옆면 다각형 안인지 본다
function hitColumn(x, y) {
for (let s = (GRID - 1) * 2; s >= 0; s -= 1) {
for (let i = 0; i < N; i += 1) {
if (i % GRID + Math.floor(i / GRID) !== s) {
continue;
}
const c = cellOf(i);
const shape = [project(c[0], c[1], hgt[i]), project(c[2], c[1], hgt[i]), project(c[2], c[1], 0), project(c[2], c[3], 0), project(c[0], c[3], 0), project(c[0], c[3], hgt[i])];
if (inside([x, y], shape)) {
return i;
}
}
}
return -1;
}
cv.addEventListener('pointermove', function (ev) {
if (demo) {
return;
}
// 포인터가 판 가운데에서 어느 쪽에 있는지로 빛 방위각을 정한다 (화면 → 바닥 좌표로 되돌려 atan2)
const p = toScene(ev);
const dx = (p[0] - OX) / cosA;
const dy = (p[1] - (OY + GRID * CELL * sinA)) / sinA;
const wx = (dx + dy) / 2;
const wy = (dy - dx) / 2;
azimuth = (Math.atan2(wy, wx) / DEG + 360) % 360;
aiming = true;
if (still) {
draw();
}
});
cv.addEventListener('pointerleave', function () { aiming = false; });
bindKeys(function (d) { sel = nextIdx(focusIdx(), d, N); }, after);
bindPointer(hitColumn, after);
if (spinBtn) {
spinBtn.addEventListener('click', function () { wake(); spinning = !spinning; if (still) {
azimuth = (azimuth + 45) % 360;
} after(); });
}
if (dataBtn) {
dataBtn.addEventListener('click', function () { wake(); seed += 1; goal = seededValues(seed, N, 18, 100); after(); });
}
report();
let rafId = 0;
let lastTs = -1;
let acc = 0;
let clock = 0;
function frame(ts) {
if (lastTs < 0) {
lastTs = ts;
}
// 탭이 숨었다 돌아와도 한 번에 100ms 까지만 따라잡는다 — 순간이동 대신 이어서 움직인다
acc += Math.min(ts - lastTs, 100);
lastTs = ts;
let n = 0;
while (acc >= FIXED_DT && n < 6) {
clock += FIXED_DT;
if (demo) {
demoTick(clock);
}
step();
acc -= FIXED_DT;
n += 1;
}
draw();
rafId = window.requestAnimationFrame(frame);
}
function startMotion() {
window.cancelAnimationFrame(rafId);
lastTs = -1;
acc = 0;
if (still) {
// 움직임 줄이기 — 루프를 돌리지 않고 지금 목표 상태로 바로 그린다
settle();
draw();
}
else {
rafId = window.requestAnimationFrame(frame);
}
}
// 열린 페이지에서 움직임 줄이기 설정이 바뀌어도 그 자리에서 루프를 멈추거나 다시 켠다
function onMotionPref() {
still = reduceQuery.matches;
startMotion();
}
if (typeof reduceQuery.addEventListener === 'function') {
reduceQuery.addEventListener('change', onMotionPref);
}
startMotion();
return function () {
window.cancelAnimationFrame(rafId);
window.removeEventListener('resize', onResize);
if (typeof reduceQuery.removeEventListener === 'function') {
reduceQuery.removeEventListener('change', onMotionPref);
}
};
})();// BarIsometricColumnShade - vanilla 판(07-bar-chart-isometric-column-shade) 의 React 포트. 같은 계산을 useEffect 안에서 돌린다.
import { useEffect, useRef } from "react";
import styles from "./BarIsometricColumnShade.module.scss";
const cx = (s: string): string => s.split(" ").map((n) => styles[n] ?? n).join(" ");
export default function BarIsometricColumnShade() {
const rootRef = useRef<HTMLDivElement | null>(null);
useEffect(() => {
const rootEl = rootRef.current;
if (!rootEl) return;
const root: HTMLElement = rootEl;
type RGB = [number, number, number];
const W = 480;
const H = 300;
const FIXED_DT = 16;
const TAU = Math.PI * 2;
// 파스텔 팔레트 — 어두운 무대 위에 밝은 막대를 얹어 명도 차로 경계가 읽힌다
const BG: RGB = [24, 26, 38];
const PANEL: RGB = [36, 39, 56];
const PAPER: RGB = [250, 246, 236];
const INK: RGB = [30, 30, 44];
const PAL: RGB[] = [
[126, 190, 255],
[255, 164, 190],
[130, 224, 190],
[192, 168, 255],
[255, 206, 160],
[244, 226, 140],
[150, 220, 236],
[230, 184, 226],
[196, 220, 160],
[176, 196, 236],
];
// 가상 데이터의 이름 — 실제 항목이 아니라 순서만 뜻한다
const LABELS = ['항목 A', '항목 B', '항목 C', '항목 D', '항목 E', '항목 F', '항목 G', '항목 H', '항목 I', '항목 J'];
function clamp(v: number, lo: number, hi: number): number { return v < lo ? lo : (v > hi ? hi : v); }
function lerp(a: number, b: number, k: number): number { return a + (b - a) * k; }
function smooth(x: number): number { const c = clamp(x, 0, 1); return c * c * (3 - 2 * c); }
function rgba(c: RGB, a: number): string {
return 'rgba(' + Math.round(c[0]) + ',' + Math.round(c[1]) + ',' + Math.round(c[2]) + ',' + clamp(a, 0, 1).toFixed(3) + ')';
}
function mix(a: RGB, b: RGB, k: number): RGB { return [lerp(a[0], b[0], k), lerp(a[1], b[1], k), lerp(a[2], b[2], k)]; }
const canvasEl = root.querySelector('[data-role="canvas"]') as HTMLCanvasElement | null;
const statusEl = root.querySelector('[data-role="status"]') as HTMLElement | null;
const ctxRaw = canvasEl ? canvasEl.getContext('2d') : null;
if (!canvasEl || !ctxRaw || !statusEl) { return; }
const cv: HTMLCanvasElement = canvasEl;
const ctx: CanvasRenderingContext2D = ctxRaw;
const status: HTMLElement = statusEl;
const reduceQuery = window.matchMedia('(prefers-reduced-motion: reduce)');
// 움직임 줄이기 — 열린 페이지에서 설정을 바꿔도 아래 tail 의 change 리스너가 이 값을 다시 읽는다
let still = reduceQuery.matches;
// 자동 시연 중인가 — 사람이 처음 만지는 순간 시연을 멈추고 상태 줄을 읽어 주기 시작한다
let demo = root.classList.contains('is-demo');
function wake(): void {
if (!demo) { return; }
demo = false;
root.classList.remove('is-demo');
status.setAttribute('aria-live', 'polite');
}
function say(text: string): void {
if (status.textContent !== text) { status.textContent = text; }
}
function fitCanvas(): void {
// 배율은 2 에서 자른다 — 배율 3 기기에서 화소가 2.25배로 늘어 프레임마다 일이 그만큼 커지지 않게
const dpr = Math.min(window.devicePixelRatio || 1, 2);
cv.width = Math.round(W * dpr);
cv.height = Math.round(H * dpr);
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
}
function onResize(): void {
fitCanvas();
draw();
}
fitCanvas();
window.addEventListener('resize', onResize);
// 화면 좌표(CSS px) → 장면 좌표(480x300). 리사이즈 뒤에도 늘 현재 크기로 다시 잰다
function toScene(ev: PointerEvent): [number, number] {
const r = cv.getBoundingClientRect();
return [((ev.clientX - r.left) / r.width) * W, ((ev.clientY - r.top) / r.height) * H];
}
// 시드 고정 난수 — 같은 시드면 같은 가상 데이터가 다시 나온다 (32비트 정수 섞기)
function makeRng(seed: number): () => number {
let s = seed >>> 0;
return function (): number {
s = (s + 0x6d2b79f5) >>> 0;
let t = s;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function seededValues(seed: number, n: number, lo: number, hi: number): number[] {
const rnd = makeRng(seed);
const out: number[] = [];
for (let i = 0; i < n; i += 1) { out.push(lo + Math.floor(rnd() * (hi - lo + 1))); }
return out;
}
// 세 자리마다 쉼표 — 지역 설정에 기대지 않는다
function groupDigits(n: number): string {
const s = String(Math.round(Math.abs(n)));
let out = '';
for (let i = 0; i < s.length; i += 1) {
if (i > 0 && (s.length - i) % 3 === 0) { out += ','; }
out += s[i];
}
return (n < 0 ? '-' : '') + out;
}
// 세로 막대 경로 — 기준선 base 에서 h 만큼(음수면 아래로) 뻗고, 끝 모서리만 둥글린다
function barPath(c: CanvasRenderingContext2D, x: number, base: number, w: number, h: number, r: number): void {
const rr = Math.min(r, Math.abs(h), w / 2);
const tip = base - h;
const s = h >= 0 ? 1 : -1;
c.beginPath();
c.moveTo(x, base);
c.lineTo(x, tip + s * rr);
c.quadraticCurveTo(x, tip, x + rr, tip);
c.lineTo(x + w - rr, tip);
c.quadraticCurveTo(x + w, tip, x + w, tip + s * rr);
c.lineTo(x + w, base);
c.closePath();
}
// 가로 막대 경로 — 왼쪽 x0 에서 len 만큼 뻗고 오른쪽 끝만 둥글린다
function hbarPath(c: CanvasRenderingContext2D, x0: number, y: number, len: number, th: number, r: number): void {
const rr = Math.min(r, Math.max(len, 0), th / 2);
const x1 = x0 + Math.max(len, 0);
c.beginPath();
c.moveTo(x0, y);
c.lineTo(x1 - rr, y);
c.quadraticCurveTo(x1, y, x1, y + rr);
c.lineTo(x1, y + th - rr);
c.quadraticCurveTo(x1, y + th, x1 - rr, y + th);
c.lineTo(x0, y + th);
c.closePath();
}
function clearStage(): void {
ctx.fillStyle = rgba(BG, 1);
ctx.fillRect(0, 0, W, H);
}
function axisText(text: string, x: number, y: number, align: CanvasTextAlign, a: number): void {
ctx.font = '500 10px sans-serif';
ctx.textAlign = align;
ctx.textBaseline = 'middle';
ctx.fillStyle = rgba(PAPER, a);
ctx.fillText(text, x, y);
}
// 고른 막대 — 화살표 키·포인터가 가리키는 sel 과 Enter·Space·클릭으로 고정한 pinned
let sel = -1;
let pinned = -1;
function focusIdx(): number { return sel >= 0 ? sel : pinned; }
function nextIdx(cur: number, d: number, n: number): number {
return cur < 0 ? (d > 0 ? 0 : n - 1) : (cur + d + n) % n;
}
function togglePin(i: number): void {
pinned = i < 0 || pinned === i ? -1 : i;
}
// 고른 막대 테두리 — 화살표·포인터로 가리키기만 하면 점선, Enter·Space·클릭으로 고정하면 실선
function ringStyle(i: number, a: number): void {
ctx.strokeStyle = rgba(PAPER, 0.95 * a);
ctx.lineWidth = 2;
ctx.setLineDash(i === pinned ? [] : [4, 3]);
}
// 키보드 — ←/→ 막대 옮기기, Enter·Space 고르기, Esc 풀기. 셋 다 상태 줄이 이름과 값을 읽는다
function bindKeys(move: (d: number) => void, changed: () => void): void {
cv.addEventListener('keydown', function (ev: KeyboardEvent): void {
if (ev.key === 'ArrowRight' || ev.key === 'ArrowLeft') {
ev.preventDefault();
wake();
move(ev.key === 'ArrowRight' ? 1 : -1);
changed();
} else if (ev.key === 'Enter' || ev.key === ' ') {
ev.preventDefault();
wake();
togglePin(focusIdx());
changed();
} else if (ev.key === 'Escape') {
ev.preventDefault();
wake();
sel = -1;
pinned = -1;
changed();
}
});
}
// 포인터 — 올리면 sel, 누르면 그 막대를 고정(같은 막대를 다시 누르면 풀기)
function bindPointer(hit: (x: number, y: number) => number, changed: () => void): void {
cv.addEventListener('pointermove', function (ev: PointerEvent): void {
if (demo) { return; }
const p = toScene(ev);
const i = hit(p[0], p[1]);
if (i !== sel) { sel = i; changed(); }
});
cv.addEventListener('pointerdown', function (ev: PointerEvent): void {
wake();
const p = toScene(ev);
const i = hit(p[0], p[1]);
sel = i;
togglePin(i);
changed();
});
}
// 시연 일정 — 루프 안의 시각(ms) 표를 지날 때마다 한 번씩 부른다
let schedCycle = -1;
let schedIdx = 0;
function runSchedule(t: number, loop: number, marks: number[], fire: (k: number, cycle: number) => void): void {
const cyc = Math.floor(t / loop);
const p = t - cyc * loop;
if (cyc !== schedCycle) { schedCycle = cyc; schedIdx = 0; }
while (schedIdx < marks.length && p >= marks[schedIdx]) {
fire(schedIdx, cyc);
schedIdx += 1;
}
}
// 등축 투영 각 — 바닥의 x·y 축이 화면 가로에서 이 각만큼 기운다 (cos 는 가로, sin 은 세로 몫)
const ISO_ANGLE_DEG = 30;
// 빛이 오는 방향 — 바닥 평면에서 +x 축을 0° 로 잰 방위각. 시연·포인터가 이 값에서 출발해 돌린다
const LIGHT_AZIMUTH_DEG = 135;
// 기둥 바닥의 한 변(px) — 칸 CELL 보다 작아 기둥 사이에 길이 생긴다
const DEPTH_PX = 24;
const LIGHT_ELEV_DEG = 42;
const AMBIENT = 0.3;
const GRID = 4;
const CELL = 34;
const SEED = 4707;
const OX = 240;
const OY = 134;
const HEIGHT_LERP = 0.12;
const SPIN_DEG_PER_S = 180;
const DEMO_LOOP = 2000;
const ROWS = ['A', 'B', 'C', 'D'];
const TXT_IDLE = '←/→ 로 기둥 고르기';
const spinBtn = root.querySelector('[data-role="spin"]') as HTMLButtonElement | null;
const dataBtn = root.querySelector('[data-role="data"]') as HTMLButtonElement | null;
const DEG = Math.PI / 180;
const cosA = Math.cos(ISO_ANGLE_DEG * DEG);
const sinA = Math.sin(ISO_ANGLE_DEG * DEG);
const N = GRID * GRID;
let seed = SEED;
let goal: number[] = seededValues(seed, N, 18, 100);
const hgt: number[] = goal.map(function (): number { return 0; });
let azimuth = LIGHT_AZIMUTH_DEG;
let spinning = true;
let aiming = false;
type P2 = [number, number];
// 등축 투영 — 바닥 (wx, wy) 와 높이 wz 를 화면 점으로
function project(wx: number, wy: number, wz: number): P2 {
return [OX + (wx - wy) * cosA, OY + (wx + wy) * sinA - wz];
}
// 빛 벡터 — 방위각과 고도에서 단위 벡터 (Lx, Ly, Lz)
function lightVec(): [number, number, number] {
const az = azimuth * DEG;
const el = LIGHT_ELEV_DEG * DEG;
return [Math.cos(el) * Math.cos(az), Math.cos(el) * Math.sin(az), Math.sin(el)];
}
// 면 밝기 — 바탕 빛 AMBIENT 에 법선·빛 내적(음수면 0)을 더한다
function shade(nx: number, ny: number, nz: number, L: [number, number, number]): number {
return AMBIENT + (1 - AMBIENT) * Math.max(0, nx * L[0] + ny * L[1] + nz * L[2]);
}
function tone(c: RGB, b: number): RGB { return [clamp(c[0] * b, 0, 255), clamp(c[1] * b, 0, 255), clamp(c[2] * b, 0, 255)]; }
function poly(pts: P2[]): void {
ctx.beginPath();
ctx.moveTo(pts[0][0], pts[0][1]);
for (let i = 1; i < pts.length; i += 1) { ctx.lineTo(pts[i][0], pts[i][1]); }
ctx.closePath();
}
// 볼록 껍질 — 바닥 네 점과 그림자로 옮긴 네 점을 한 덩어리 그림자로 감싼다
function hull(ps: P2[]): P2[] {
const p = ps.slice().sort(function (a: P2, b: P2): number { return a[0] - b[0] || a[1] - b[1]; });
const cross = function (o: P2, a: P2, b: P2): number { return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]); };
const lo: P2[] = [];
for (let i = 0; i < p.length; i += 1) { while (lo.length >= 2 && cross(lo[lo.length - 2], lo[lo.length - 1], p[i]) <= 0) { lo.pop(); } lo.push(p[i]); }
const up: P2[] = [];
for (let i = p.length - 1; i >= 0; i -= 1) { while (up.length >= 2 && cross(up[up.length - 2], up[up.length - 1], p[i]) <= 0) { up.pop(); } up.push(p[i]); }
lo.pop();
up.pop();
return lo.concat(up);
}
function cellOf(i: number): [number, number, number, number] {
const gx = i % GRID;
const gy = Math.floor(i / GRID);
const x0 = gx * CELL + (CELL - DEPTH_PX) / 2;
const y0 = gy * CELL + (CELL - DEPTH_PX) / 2;
return [x0, y0, x0 + DEPTH_PX, y0 + DEPTH_PX];
}
function step(): void {
for (let i = 0; i < N; i += 1) { hgt[i] += (goal[i] - hgt[i]) * HEIGHT_LERP; }
if (spinning && !aiming) { azimuth = (azimuth + SPIN_DEG_PER_S * FIXED_DT / 1000) % 360; }
}
function settle(): void {
for (let i = 0; i < N; i += 1) { hgt[i] = goal[i]; }
}
function nameOf(i: number): string { return ROWS[Math.floor(i / GRID)] + String((i % GRID) + 1); }
function report(): void {
const f = focusIdx();
if (f >= 0) { say(nameOf(f) + ' · ' + groupDigits(goal[f])); } else { say(TXT_IDLE); }
}
function demoTick(t: number): void {
// 시연 — 빛이 한 바퀴 반을 돌고, 루프 처음에 기둥이 바닥에서 솟는다
runSchedule(t, DEMO_LOOP, [200], function (): void {
for (let i = 0; i < N; i += 1) { hgt[i] = 0; }
});
}
function draw(): void {
clearStage();
const L = lightVec();
const ext = GRID * CELL;
// 바닥 판
ctx.fillStyle = rgba(PANEL, 1);
poly([project(0, 0, 0), project(ext, 0, 0), project(ext, ext, 0), project(0, ext, 0)]);
ctx.fill();
// 그림자 — 높이 h 인 꼭대기를 빛 반대쪽으로 h·(Lx, Ly)/Lz 만큼 바닥에 눕힌다
ctx.fillStyle = 'rgba(6,6,14,0.38)';
for (let i = 0; i < N; i += 1) {
const c = cellOf(i);
const h = hgt[i];
const sx = -h * L[0] / L[2];
const sy = -h * L[1] / L[2];
const base: P2[] = [[c[0], c[1]], [c[2], c[1]], [c[2], c[3]], [c[0], c[3]]];
const pts: P2[] = [];
for (let k = 0; k < 4; k += 1) { pts.push(base[k]); pts.push([base[k][0] + sx, base[k][1] + sy]); }
poly(hull(pts).map(function (q: P2): P2 { return project(clamp(q[0], 0, ext), clamp(q[1], 0, ext), 0); }));
ctx.fill();
}
// 뒤에서 앞으로 — gx + gy 가 작은 칸(화면 위쪽)부터 그려 앞 기둥이 뒤 기둥을 가린다
const order: number[] = [];
for (let i = 0; i < N; i += 1) { order.push(i); }
order.sort(function (a: number, b: number): number { return (a % GRID + Math.floor(a / GRID)) - (b % GRID + Math.floor(b / GRID)); });
const f = focusIdx();
const bTop = shade(0, 0, 1, L);
const bRight = shade(1, 0, 0, L);
const bLeft = shade(0, 1, 0, L);
for (let n = 0; n < N; n += 1) {
const i = order[n];
const c = cellOf(i);
const z = hgt[i] + (i === f ? 6 : 0);
const col = PAL[(i % GRID + Math.floor(i / GRID)) % PAL.length];
const dim = f >= 0 && f !== i ? 0.6 : 1;
// +y 쪽 면(화면 왼쪽 아래)
ctx.fillStyle = rgba(tone(col, bLeft * 1.1), dim);
poly([project(c[0], c[3], 0), project(c[2], c[3], 0), project(c[2], c[3], z), project(c[0], c[3], z)]);
ctx.fill();
// +x 쪽 면(화면 오른쪽 아래)
ctx.fillStyle = rgba(tone(col, bRight * 1.1), dim);
poly([project(c[2], c[1], 0), project(c[2], c[3], 0), project(c[2], c[3], z), project(c[2], c[1], z)]);
ctx.fill();
// 윗면
ctx.fillStyle = rgba(tone(col, bTop * 1.1), dim);
poly([project(c[0], c[1], z), project(c[2], c[1], z), project(c[2], c[3], z), project(c[0], c[3], z)]);
ctx.fill();
if (i === f) {
ringStyle(i, 1);
ctx.stroke();
ctx.setLineDash([]);
const tp = project((c[0] + c[2]) / 2, (c[1] + c[3]) / 2, z);
ctx.font = '700 11px sans-serif';
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
ctx.fillStyle = rgba(PAPER, 0.95);
ctx.fillText(nameOf(i) + ' ' + groupDigits(goal[i]), tp[0], tp[1] - 6);
}
}
// 빛 나침반 — 오른쪽 아래, 바닥 평면에서 빛이 오는 쪽을 가리킨다
const cx = 428;
const cy = 252;
const tip = project(Math.cos(azimuth * DEG) * 22, Math.sin(azimuth * DEG) * 22, 0);
const org = project(0, 0, 0);
ctx.strokeStyle = rgba(PAPER, 0.25);
ctx.lineWidth = 1;
ctx.beginPath();
ctx.ellipse(cx, cy, 22 * cosA * 1.41, 22 * sinA * 1.41, 0, 0, TAU);
ctx.stroke();
ctx.fillStyle = rgba(PAL[5], 1);
ctx.beginPath();
ctx.arc(cx + tip[0] - org[0], cy + tip[1] - org[1], 4, 0, TAU);
ctx.fill();
axisText(Math.round(azimuth) + '°', cx, cy, 'center', 0.7);
}
function after(): void {
if (still) { settle(); }
report();
draw();
if (spinBtn) { spinBtn.setAttribute('aria-pressed', spinning ? 'false' : 'true'); }
}
function inside(pt: P2, pts: P2[]): boolean {
let hit = false;
for (let i = 0, j = pts.length - 1; i < pts.length; j = i, i += 1) {
const a = pts[i];
const b = pts[j];
if ((a[1] > pt[1]) !== (b[1] > pt[1]) && pt[0] < (b[0] - a[0]) * (pt[1] - a[1]) / (b[1] - a[1]) + a[0]) { hit = !hit; }
}
return hit;
}
// 포인터 자리의 기둥 — 앞 칸부터 윗면·옆면 다각형 안인지 본다
function hitColumn(x: number, y: number): number {
for (let s = (GRID - 1) * 2; s >= 0; s -= 1) {
for (let i = 0; i < N; i += 1) {
if (i % GRID + Math.floor(i / GRID) !== s) { continue; }
const c = cellOf(i);
const shape: P2[] = [project(c[0], c[1], hgt[i]), project(c[2], c[1], hgt[i]), project(c[2], c[1], 0), project(c[2], c[3], 0), project(c[0], c[3], 0), project(c[0], c[3], hgt[i])];
if (inside([x, y], shape)) { return i; }
}
}
return -1;
}
cv.addEventListener('pointermove', function (ev: PointerEvent): void {
if (demo) { return; }
// 포인터가 판 가운데에서 어느 쪽에 있는지로 빛 방위각을 정한다 (화면 → 바닥 좌표로 되돌려 atan2)
const p = toScene(ev);
const dx = (p[0] - OX) / cosA;
const dy = (p[1] - (OY + GRID * CELL * sinA)) / sinA;
const wx = (dx + dy) / 2;
const wy = (dy - dx) / 2;
azimuth = (Math.atan2(wy, wx) / DEG + 360) % 360;
aiming = true;
if (still) { draw(); }
});
cv.addEventListener('pointerleave', function (): void { aiming = false; });
bindKeys(function (d: number): void { sel = nextIdx(focusIdx(), d, N); }, after);
bindPointer(hitColumn, after);
if (spinBtn) { spinBtn.addEventListener('click', function (): void { wake(); spinning = !spinning; if (still) { azimuth = (azimuth + 45) % 360; } after(); }); }
if (dataBtn) { dataBtn.addEventListener('click', function (): void { wake(); seed += 1; goal = seededValues(seed, N, 18, 100); after(); }); }
report();
let rafId = 0;
let lastTs = -1;
let acc = 0;
let clock = 0;
function frame(ts: number): void {
if (lastTs < 0) { lastTs = ts; }
// 탭이 숨었다 돌아와도 한 번에 100ms 까지만 따라잡는다 — 순간이동 대신 이어서 움직인다
acc += Math.min(ts - lastTs, 100);
lastTs = ts;
let n = 0;
while (acc >= FIXED_DT && n < 6) {
clock += FIXED_DT;
if (demo) { demoTick(clock); }
step();
acc -= FIXED_DT;
n += 1;
}
draw();
rafId = window.requestAnimationFrame(frame);
}
function startMotion(): void {
window.cancelAnimationFrame(rafId);
lastTs = -1;
acc = 0;
if (still) {
// 움직임 줄이기 — 루프를 돌리지 않고 지금 목표 상태로 바로 그린다
settle();
draw();
} else {
rafId = window.requestAnimationFrame(frame);
}
}
// 열린 페이지에서 움직임 줄이기 설정이 바뀌어도 그 자리에서 루프를 멈추거나 다시 켠다
function onMotionPref(): void {
still = reduceQuery.matches;
startMotion();
}
if (typeof reduceQuery.addEventListener === 'function') { reduceQuery.addEventListener('change', onMotionPref); }
startMotion();
return function (): void {
window.cancelAnimationFrame(rafId);
window.removeEventListener('resize', onResize);
if (typeof reduceQuery.removeEventListener === 'function') { reduceQuery.removeEventListener('change', onMotionPref); }
};
}, []);
return (
<div className={cx("bc") + " is-demo"} ref={rootRef}>
<canvas className={cx("bc__canvas")} data-role="canvas" width={480} height={300} tabIndex={0} aria-label="빛 방향에 따라 윗면과 옆면 밝기가 달라지는 등축 3D 기둥 그래프. 포인터로 빛 방향을 옮기고 ←/→ 로 기둥을 고르면 이름과 값을 읽어 준다"></canvas>
<p className={cx("bc__status")} data-role="status" aria-live="off">←/→ 로 기둥 고르기</p>
<div className={cx("bc__tools")}>
<button className={cx("bc__btn")} data-role="spin" type="button" aria-pressed="false">빛 멈춤</button>
<button className={cx("bc__btn")} data-role="data" type="button">새 데이터</button>
</div>
</div>
);
}07 Isometric 3D Columns Whose Top and Sides Shade by Light Direction — Measured area 16.805% · moving frames 23/23Original by GODRICH · SCSS and React ship in the zip · Bar Chart Animation: 9 Demos From Spring to Race
The post this demo lives in
Bar Chart Animation: 9 Demos From Spring to RaceWhen bars jump straight to new values, the eye misses what grew. So 01 grows bars on a spring that overshoots once, 02 s See all demos in this post
If you like this effect - similar demos
Dashboard UI03 A 3D Pie Chart That Tilts the Disc and Draws Its Side WallPie Chart CSS: 9 Slices That Pop, Tilt and Morph
Dashboard UI02 Column bars growing from the baselineCSS Chart Design: 9 SVG Graphs, No Library
Dashboard UI04 Candle chart whose last bar keeps growingStock Ticker UI: 9 Live Price Widgets, No API Key