Animations103 / 118
ASCII Engine
A real-time 3D renderer whose only pixels are characters. A torus, a trefoil knot and a breathing blob share one mesh, so they morph point for point. Hover and the model turns to face you while the light follows your cursor; sweep to spin it; click to send a shockwave of glitching glyphs and jump to the next shape.
Canvas 2DCanvas 2DReal 3DReal 3DZero dependenciesZero dependencies60fps60fpsReduced-motion safeReduced-motion safe
Hover to morph, sweep to spinClick for a shockwave
Tweak
LIVELIVEShapes
Torus
Trefoil knot
Breathing blob
Glyphs
11px
Colour
#4d7bff
#f2f0eb
#ff4d00
Motion
1.00
0.60
Usage
Follows your tweaks.
usage.tsx
import { AsciiEngine } from "@/components/inreact/ascii-engine";
export function Feature() {
return (
<AsciiEngine
className="h-[420px] w-full"
/>
);
}Install with the CLI
TS + Tailwind
npx shadcn@latest add https://inreact.vercel.app/r/ascii-engine.jsonTS + CSS
npx shadcn@latest add https://inreact.vercel.app/r/ascii-engine-css.jsonOr copy the source
No dependencies. Save this as components/inreact/ascii-engine.tsx.
components/inreact/ascii-engine.tsx
"use client";
import { useEffect, useRef } from "react";
/**
* ASCII Engine: a real-time 3D renderer whose only pixels are characters.
*
* Three surfaces share one (u, v) grid, so they morph point for point:
* torus, trefoil knot, breathing blob. Hover to morph and the model turns to
* face you while the light follows your cursor; sweep to spin it; click to
* send a shockwave of glitching glyphs and jump to the next shape.
*
* <AsciiEngine className="h-[420px] w-full" />
*
* Canvas 2D, no dependencies. Glyphs are drawn from a pre-rendered atlas, so
* thousands of characters stay at 60fps. Pauses off-screen; reduced motion
* stops the idle spin and the glitches.
*/
export type AsciiShape = "torus" | "knot" | "blob";
export interface AsciiEngineProps {
/** Shapes to morph between, in order. */
shapes?: AsciiShape[];
/** Characters from darkest to brightest. */
ramp?: string;
/** Shadow, body, highlight and hot-spot colours. */
colors?: [string, string, string, string];
/** Character size in px. */
fontSize?: number;
/** Monospace font family for the glyphs. */
font?: string;
/** Idle spin speed multiplier. */
speed?: number;
/** Fade far parts of the model (depth). 0 = off, 1 = full. */
depth?: number;
className?: string;
}
const U = 170;
const V = 38;
const N = U * V;
const TAU = Math.PI * 2;
type Mesh = { p: Float32Array; n: Float32Array };
function torus(): Mesh {
const p = new Float32Array(N * 3);
const n = new Float32Array(N * 3);
for (let i = 0; i < U; i++)
for (let j = 0; j < V; j++) {
const u = (i / U) * TAU;
const v = (j / V) * TAU;
const k = (i * V + j) * 3;
const cx = Math.cos(u);
const sx = Math.sin(u);
n[k] = Math.cos(v) * cx;
n[k + 1] = Math.cos(v) * sx;
n[k + 2] = Math.sin(v);
p[k] = (1 + 0.42 * Math.cos(v)) * cx;
p[k + 1] = (1 + 0.42 * Math.cos(v)) * sx;
p[k + 2] = 0.42 * Math.sin(v);
}
return { p, n };
}
function knot(): Mesh {
const p = new Float32Array(N * 3);
const n = new Float32Array(N * 3);
const c = (t: number) => {
const r = 2 + Math.cos(3 * t);
return [r * Math.cos(2 * t) * 0.42, r * Math.sin(2 * t) * 0.42, Math.sin(3 * t) * 0.42];
};
for (let i = 0; i < U; i++) {
const t = (i / U) * TAU;
const a = c(t);
const b = c(t + 0.001);
let tx = b[0] - a[0];
let ty = b[1] - a[1];
let tz = b[2] - a[2];
const tl = Math.hypot(tx, ty, tz);
tx /= tl;
ty /= tl;
tz /= tl;
let nx = ty;
let ny = -tx;
const nz = 0;
const nl = Math.hypot(nx, ny) || 1;
nx /= nl;
ny /= nl;
const bx = ty * nz - tz * ny;
const by = tz * nx - tx * nz;
const bz = tx * ny - ty * nx;
for (let j = 0; j < V; j++) {
const v = (j / V) * TAU;
const cv = Math.cos(v);
const sv = Math.sin(v);
const k = (i * V + j) * 3;
n[k] = cv * nx + sv * bx;
n[k + 1] = cv * ny + sv * by;
n[k + 2] = cv * nz + sv * bz;
p[k] = a[0] + 0.2 * n[k];
p[k + 1] = a[1] + 0.2 * n[k + 1];
p[k + 2] = a[2] + 0.2 * n[k + 2];
}
}
return { p, n };
}
/** Sphere with travelling bumps; recomputed every frame. */
function blob(out: Mesh, time: number) {
for (let i = 0; i < U; i++)
for (let j = 0; j < V; j++) {
const phi = (i / U) * TAU;
const th = ((j + 0.5) / V) * Math.PI;
const k = (i * V + j) * 3;
const sx = Math.sin(th) * Math.cos(phi);
const sy = Math.sin(th) * Math.sin(phi);
const sz = Math.cos(th);
const r = 1.05 + 0.2 * Math.sin(3 * th + time * 1.4) * Math.sin(4 * phi - time);
out.p[k] = sx * r;
out.p[k + 1] = sy * r;
out.p[k + 2] = sz * r;
out.n[k] = sx;
out.n[k + 1] = sy;
out.n[k + 2] = sz;
}
}
const ease = (t: number) => (t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2);
const isReducedMotion = () =>
typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
export function AsciiEngine({
shapes = ["torus", "knot", "blob"],
ramp = ".,-~:;=!*#$@",
colors = ["rgba(242,240,235,0.32)", "#4d7bff", "#f2f0eb", "#ff4d00"],
fontSize,
font = "ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",
speed = 1,
depth = 0.6,
className,
}: AsciiEngineProps) {
const hostRef = useRef<HTMLDivElement>(null);
const canvasRef = useRef<HTMLCanvasElement>(null);
const live = useRef({ shapes, ramp, colors, fontSize, font, speed, depth });
const reset = useRef<(() => void) | null>(null);
// keyed by content, so inline arrays from a parent don't reset the morph every render
const shapesKey = shapes.join();
const colorsKey = colors.join();
useEffect(() => {
live.current = { shapes, ramp, colors, fontSize, font, speed, depth };
});
useEffect(() => {
reset.current?.();
}, [shapesKey, ramp, colorsKey, fontSize, font]);
useEffect(() => {
const host = hostRef.current;
const canvas = canvasRef.current;
if (!host || !canvas) return;
if (getComputedStyle(host).position === "static") host.style.position = "relative";
const ctx = canvas.getContext("2d")!;
const reduced = isReducedMotion();
const meshes: Record<AsciiShape, Mesh> = {
torus: torus(),
knot: knot(),
blob: { p: new Float32Array(N * 3), n: new Float32Array(N * 3) },
};
const s = {
from: 0, to: 0, morph: 1, ax: -0.5, ay: 0.4, vx: 0, vy: 0.6, t: 0,
over: false, lx: 0, ly: 0, cx: -1e4, cy: -1e4, hx: 0, hy: 0, sx: 0, sy: 0, hov: 0,
};
// click shockwaves: centre (css px) and start time
const waves: { x: number; y: number; t0: number }[] = [];
/* ---------- the glyph atlas: every character in every colour, pre-rendered ---------- */
let atlas = document.createElement("canvas");
let cw = 6.6, ch = 11.55, fs = 11, dpr = 1, atlasKey = "";
const palette = () => {
const L = live.current;
return [...L.colors, "rgba(242,240,235,0.22)"]; // last one: faint scanner flicker
};
const fontFamily = () => {
const f = live.current.font;
const m = f.match(/^var\((--[\w-]+)\)/);
return m ? getComputedStyle(document.documentElement).getPropertyValue(m[1]).trim() || "monospace" : f;
};
const buildAtlas = () => {
const L = live.current;
const pal = palette();
const key = [fs, dpr, L.ramp, pal.join(), L.font].join("|");
if (key === atlasKey) return;
atlasKey = key;
atlas = document.createElement("canvas");
atlas.width = Math.ceil(cw * dpr) * L.ramp.length;
atlas.height = Math.ceil(ch * dpr) * pal.length;
const a = atlas.getContext("2d")!;
a.setTransform(dpr, 0, 0, dpr, 0, 0);
a.font = `600 ${fs}px ${fontFamily()}`;
a.textBaseline = "top";
const gw = Math.ceil(cw * dpr) / dpr;
const gh = Math.ceil(ch * dpr) / dpr;
pal.forEach((col, ci) => {
a.fillStyle = col;
for (let gi = 0; gi < L.ramp.length; gi++) a.fillText(L.ramp[gi], gi * gw, ci * gh);
});
};
/* ---------- reusable per-frame buffers ---------- */
let w = 1, h = 1, cols = 1, rows = 1, cells = 1;
let zbuf = new Float32Array(1);
let lum = new Float32Array(1);
let glitch = new Uint8Array(1);
let gchar = new Uint8Array(1);
const resize = () => {
dpr = Math.min(window.devicePixelRatio || 1, 2);
w = Math.max(1, canvas.clientWidth);
h = Math.max(1, canvas.clientHeight);
canvas.width = Math.round(w * dpr);
canvas.height = Math.round(h * dpr);
fs = live.current.fontSize ?? (w < 420 ? 9 : 11);
cw = fs * 0.6;
ch = fs * 1.05;
cols = Math.max(1, Math.floor(w / cw));
rows = Math.max(1, Math.floor(h / ch));
cells = cols * rows;
zbuf = new Float32Array(cells);
lum = new Float32Array(cells);
glitch = new Uint8Array(cells);
gchar = new Uint8Array(cells);
buildAtlas();
};
resize();
reset.current = () => {
resize();
s.from = s.to = 0;
s.morph = 1;
};
/* ---------- input ---------- */
let lastMorph = -10;
const next = () => {
const count = Math.max(1, live.current.shapes.length);
s.from = s.to;
s.to = (s.to + 1) % count;
s.morph = reduced ? 1 : 0;
lastMorph = s.t;
};
const enter = (e: PointerEvent) => {
s.lx = e.clientX;
s.ly = e.clientY;
s.over = true;
if (s.morph >= 1 && s.t - lastMorph > 1.2) next();
};
const move = (e: PointerEvent) => {
const r = canvas.getBoundingClientRect();
s.cx = e.clientX - r.left;
s.cy = e.clientY - r.top;
s.hx = (s.cx / r.width) * 2 - 1;
s.hy = (s.cy / r.height) * 2 - 1;
s.over = true;
const dx = e.clientX - s.lx;
const dy = e.clientY - s.ly;
s.lx = e.clientX;
s.ly = e.clientY;
if (Math.abs(dx) > 80 || Math.abs(dy) > 80) return;
s.vy = Math.max(-9, Math.min(9, s.vy + dx * 0.06));
s.vx = Math.max(-9, Math.min(9, s.vx + dy * 0.06));
};
const leave = () => {
s.over = false;
s.hx = 0;
s.hy = 0;
};
const click = (e: PointerEvent) => {
if (reduced) return;
const r = canvas.getBoundingClientRect();
waves.push({ x: e.clientX - r.left, y: e.clientY - r.top, t0: s.t });
if (waves.length > 4) waves.shift();
if (s.morph >= 1) next();
};
host.addEventListener("pointerenter", enter);
host.addEventListener("pointermove", move);
host.addEventListener("pointerleave", leave);
host.addEventListener("pointerdown", click);
/* ---------- one frame ---------- */
const frame = (dt: number) => {
const L = live.current;
const list = L.shapes.length ? L.shapes : (["torus"] as AsciiShape[]);
s.t += dt;
const pull = Math.min(1, dt * (s.over ? 0.9 : 1.5));
s.vy += ((reduced ? 0 : 0.6 * L.speed) - s.vy) * pull;
s.vx += ((reduced ? 0 : 0.15 * L.speed) - s.vx) * pull;
s.ay += s.vy * dt;
s.ax += s.vx * dt;
if (s.morph < 1) s.morph = Math.min(1, s.morph + dt / 1.4);
s.hov += ((s.over ? 1 : 0) - s.hov) * Math.min(1, dt * 4);
const follow = Math.min(1, dt * 6);
s.sx += (s.hx - s.sx) * follow;
s.sy += (s.hy - s.sy) * follow;
if (list.includes("blob")) blob(meshes.blob, reduced ? 0 : s.t);
zbuf.fill(0);
lum.fill(-2);
glitch.fill(0);
const k = Math.min(cols * 0.42, rows * (ch / cw) * 0.62) * 1.75 * (1 + 0.14 * s.hov);
const A = meshes[list[s.from % list.length]];
const B = meshes[list[s.to % list.length]];
const m = ease(s.morph);
// the model turns to face the pointer while hovered
const rx = s.ax + s.sy * 0.75 * s.hov;
const ry = s.ay + s.sx * 0.95 * s.hov;
const ca = Math.cos(rx), sa = Math.sin(rx), cb = Math.cos(ry), sb = Math.sin(ry);
// light: upper-left by default; follows the cursor when hovered
let Lx = -0.45 + (s.sx * 1.2 + 0.45) * s.hov;
let Ly = 0.6 + (-s.sy * 1.2 - 0.6) * s.hov;
let Lz = -0.66 + (-0.75 + 0.66) * s.hov;
const Ll = Math.hypot(Lx, Ly, Lz) || 1;
Lx /= Ll;
Ly /= Ll;
Lz /= Ll;
for (let i = 0; i < N; i++) {
const q = i * 3;
let x = A.p[q] + (B.p[q] - A.p[q]) * m;
let y = A.p[q + 1] + (B.p[q + 1] - A.p[q + 1]) * m;
let z = A.p[q + 2] + (B.p[q + 2] - A.p[q + 2]) * m;
let nx = A.n[q] + (B.n[q] - A.n[q]) * m;
let ny = A.n[q + 1] + (B.n[q + 1] - A.n[q + 1]) * m;
let nz = A.n[q + 2] + (B.n[q + 2] - A.n[q + 2]) * m;
let t1 = x * cb + z * sb;
z = -x * sb + z * cb;
x = t1;
t1 = y * ca - z * sa;
z = y * sa + z * ca;
y = t1;
let n1 = nx * cb + nz * sb;
nz = -nx * sb + nz * cb;
nx = n1;
n1 = ny * ca - nz * sa;
nz = ny * sa + nz * ca;
ny = n1;
const ooz = 1 / (z + 4);
const px = Math.floor(cols / 2 + x * k * ooz);
// centre sits a little high so a caption never covers the model
const py = Math.floor(rows * 0.42 - y * k * ooz * (cw / ch));
if (px < 0 || px >= cols || py < 0 || py >= rows) continue;
const c = py * cols + px;
if (ooz > zbuf[c]) {
zbuf[c] = ooz;
const nl = Math.hypot(nx, ny, nz) || 1;
let l = (nx * Lx + ny * Ly + nz * Lz) / nl;
// depth: only the far half of the model recedes toward lighter glyphs;
// the front stays at full strength (ooz 0.25 = the model's centre plane)
const near = Math.min(1, Math.max(0, (ooz - 0.18) / 0.07));
l = l - (1 - near) * 0.45 * L.depth;
lum[c] = Math.max(-1, l);
}
}
const ox = (w - cols * cw) / 2;
const oy = (h - rows * ch) / 2;
// glitch halo under the cursor
if (s.hov > 0.05 && !reduced) {
const R = Math.max(60, w * 0.11);
const c0 = Math.max(0, Math.floor((s.cx - ox - R) / cw));
const c1 = Math.min(cols - 1, Math.ceil((s.cx - ox + R) / cw));
const r0 = Math.max(0, Math.floor((s.cy - oy - R) / ch));
const r1 = Math.min(rows - 1, Math.ceil((s.cy - oy + R) / ch));
for (let yy = r0; yy <= r1; yy++)
for (let xx = c0; xx <= c1; xx++) {
const d = Math.hypot(ox + (xx + 0.5) * cw - s.cx, oy + (yy + 0.5) * ch - s.cy);
const near = (1 - d / R) * s.hov;
if (near <= 0) continue;
const c = yy * cols + xx;
if (lum[c] > -1.5) {
lum[c] = Math.min(1, lum[c] + near * 0.6);
if (Math.random() < near * 0.55) {
glitch[c] = Math.random() < 0.55 ? 4 : 2; // hot or body colour
gchar[c] = Math.floor(Math.random() * L.ramp.length);
}
} else if (Math.random() < near * 0.12) {
glitch[c] = 5;
gchar[c] = Math.floor(Math.random() * L.ramp.length);
}
}
}
// click shockwaves: an expanding ring of glyph noise
for (let wi = waves.length - 1; wi >= 0; wi--) {
const wv = waves[wi];
const age = s.t - wv.t0;
const radius = age * Math.max(w, h) * 0.9;
const life = 1 - age / 1.1;
if (life <= 0) {
waves.splice(wi, 1);
continue;
}
const band = 26;
const c0 = Math.max(0, Math.floor((wv.x - ox - radius - band) / cw));
const c1 = Math.min(cols - 1, Math.ceil((wv.x - ox + radius + band) / cw));
const r0 = Math.max(0, Math.floor((wv.y - oy - radius - band) / ch));
const r1 = Math.min(rows - 1, Math.ceil((wv.y - oy + radius + band) / ch));
for (let yy = r0; yy <= r1; yy++)
for (let xx = c0; xx <= c1; xx++) {
const d = Math.hypot(ox + (xx + 0.5) * cw - wv.x, oy + (yy + 0.5) * ch - wv.y);
const on = 1 - Math.abs(d - radius) / band;
if (on <= 0 || Math.random() > on * life * 0.9) continue;
const c = yy * cols + xx;
glitch[c] = lum[c] > -1.5 ? (Math.random() < 0.5 ? 4 : 2) : 5;
gchar[c] = Math.floor(Math.random() * L.ramp.length);
}
}
/* ---------- draw from the atlas ---------- */
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, w, h);
const n = L.ramp.length;
const gw = Math.ceil(cw * dpr);
const gh = Math.ceil(ch * dpr);
const morphing = s.morph < 1;
const noise = morphing && !reduced ? 0.18 * Math.sin(Math.PI * s.morph) : 0;
for (let c = 0; c < cells; c++) {
let ci: number;
let gi: number;
if (glitch[c]) {
ci = glitch[c] - 1;
gi = gchar[c];
} else {
const l = lum[c];
if (l < -1.5) continue;
ci = l < 0.15 ? 0 : l < 0.6 ? 1 : l < 0.965 ? 2 : 3;
gi = Math.max(0, Math.min(n - 1, Math.floor(((l + 1) / 2) * n)));
// glyph noise while morphing
if (noise && Math.random() < noise) gi = Math.floor(Math.random() * n);
}
ctx.drawImage(atlas, gi * gw, ci * gh, gw, gh, ox + (c % cols) * cw, oy + Math.floor(c / cols) * ch, gw / dpr, gh / dpr);
}
};
/* ---------- loop ---------- */
let raf = 0;
let last = 0;
let visible = false;
const loop = (now: number) => {
raf = requestAnimationFrame(loop);
const dt = last ? Math.min(0.05, (now - last) / 1000) : 1 / 60;
last = now;
frame(dt);
};
const sync = () => {
const run = visible && !document.hidden;
if (run && !raf) {
last = 0;
raf = requestAnimationFrame(loop);
} else if (!run && raf) {
cancelAnimationFrame(raf);
raf = 0;
}
};
const io = new IntersectionObserver(([e]) => {
visible = e.isIntersecting;
sync();
});
io.observe(host);
document.addEventListener("visibilitychange", sync);
let lastW = canvas.clientWidth;
let lastH = canvas.clientHeight;
const ro = new ResizeObserver(() => {
if (Math.abs(canvas.clientWidth - lastW) > 2 || Math.abs(canvas.clientHeight - lastH) > 2) {
lastW = canvas.clientWidth;
lastH = canvas.clientHeight;
resize();
}
});
ro.observe(canvas);
document.fonts?.ready.then(() => {
atlasKey = "";
buildAtlas();
});
return () => {
reset.current = null;
cancelAnimationFrame(raf);
io.disconnect();
ro.disconnect();
document.removeEventListener("visibilitychange", sync);
host.removeEventListener("pointerenter", enter);
host.removeEventListener("pointermove", move);
host.removeEventListener("pointerleave", leave);
host.removeEventListener("pointerdown", click);
};
}, []);
return (
<div
ref={hostRef}
role="img"
aria-label={`A 3D ${shapes.join(", then ")} drawn in text characters`}
className={["overflow-hidden", className].filter(Boolean).join(" ")}
>
<canvas ref={canvasRef} aria-hidden="true" style={{ position: "absolute", inset: 0, width: "100%", height: "100%", display: "block" }} />
</div>
);
}
›Plain CSS variant (no Tailwind)
components/inreact/ascii-engine.tsx
"use client";
import { useEffect, useRef } from "react";
import "./ascii-engine.css";
/**
* ASCII Engine: a real-time 3D renderer whose only pixels are characters.
*
* Three surfaces share one (u, v) grid, so they morph point for point:
* torus, trefoil knot, breathing blob. Hover to morph and the model turns to
* face you while the light follows your cursor; sweep to spin it; click to
* send a shockwave of glitching glyphs and jump to the next shape.
*
* <AsciiEngine className="h-[420px] w-full" />
*
* Canvas 2D, no dependencies. Glyphs are drawn from a pre-rendered atlas, so
* thousands of characters stay at 60fps. Pauses off-screen; reduced motion
* stops the idle spin and the glitches.
*/
export type AsciiShape = "torus" | "knot" | "blob";
export interface AsciiEngineProps {
/** Shapes to morph between, in order. */
shapes?: AsciiShape[];
/** Characters from darkest to brightest. */
ramp?: string;
/** Shadow, body, highlight and hot-spot colours. */
colors?: [string, string, string, string];
/** Character size in px. */
fontSize?: number;
/** Monospace font family for the glyphs. */
font?: string;
/** Idle spin speed multiplier. */
speed?: number;
/** Fade far parts of the model (depth). 0 = off, 1 = full. */
depth?: number;
className?: string;
}
const U = 170;
const V = 38;
const N = U * V;
const TAU = Math.PI * 2;
type Mesh = { p: Float32Array; n: Float32Array };
function torus(): Mesh {
const p = new Float32Array(N * 3);
const n = new Float32Array(N * 3);
for (let i = 0; i < U; i++)
for (let j = 0; j < V; j++) {
const u = (i / U) * TAU;
const v = (j / V) * TAU;
const k = (i * V + j) * 3;
const cx = Math.cos(u);
const sx = Math.sin(u);
n[k] = Math.cos(v) * cx;
n[k + 1] = Math.cos(v) * sx;
n[k + 2] = Math.sin(v);
p[k] = (1 + 0.42 * Math.cos(v)) * cx;
p[k + 1] = (1 + 0.42 * Math.cos(v)) * sx;
p[k + 2] = 0.42 * Math.sin(v);
}
return { p, n };
}
function knot(): Mesh {
const p = new Float32Array(N * 3);
const n = new Float32Array(N * 3);
const c = (t: number) => {
const r = 2 + Math.cos(3 * t);
return [r * Math.cos(2 * t) * 0.42, r * Math.sin(2 * t) * 0.42, Math.sin(3 * t) * 0.42];
};
for (let i = 0; i < U; i++) {
const t = (i / U) * TAU;
const a = c(t);
const b = c(t + 0.001);
let tx = b[0] - a[0];
let ty = b[1] - a[1];
let tz = b[2] - a[2];
const tl = Math.hypot(tx, ty, tz);
tx /= tl;
ty /= tl;
tz /= tl;
let nx = ty;
let ny = -tx;
const nz = 0;
const nl = Math.hypot(nx, ny) || 1;
nx /= nl;
ny /= nl;
const bx = ty * nz - tz * ny;
const by = tz * nx - tx * nz;
const bz = tx * ny - ty * nx;
for (let j = 0; j < V; j++) {
const v = (j / V) * TAU;
const cv = Math.cos(v);
const sv = Math.sin(v);
const k = (i * V + j) * 3;
n[k] = cv * nx + sv * bx;
n[k + 1] = cv * ny + sv * by;
n[k + 2] = cv * nz + sv * bz;
p[k] = a[0] + 0.2 * n[k];
p[k + 1] = a[1] + 0.2 * n[k + 1];
p[k + 2] = a[2] + 0.2 * n[k + 2];
}
}
return { p, n };
}
/** Sphere with travelling bumps; recomputed every frame. */
function blob(out: Mesh, time: number) {
for (let i = 0; i < U; i++)
for (let j = 0; j < V; j++) {
const phi = (i / U) * TAU;
const th = ((j + 0.5) / V) * Math.PI;
const k = (i * V + j) * 3;
const sx = Math.sin(th) * Math.cos(phi);
const sy = Math.sin(th) * Math.sin(phi);
const sz = Math.cos(th);
const r = 1.05 + 0.2 * Math.sin(3 * th + time * 1.4) * Math.sin(4 * phi - time);
out.p[k] = sx * r;
out.p[k + 1] = sy * r;
out.p[k + 2] = sz * r;
out.n[k] = sx;
out.n[k + 1] = sy;
out.n[k + 2] = sz;
}
}
const ease = (t: number) => (t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2);
const isReducedMotion = () =>
typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
export function AsciiEngine({
shapes = ["torus", "knot", "blob"],
ramp = ".,-~:;=!*#$@",
colors = ["rgba(242,240,235,0.32)", "#4d7bff", "#f2f0eb", "#ff4d00"],
fontSize,
font = "ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",
speed = 1,
depth = 0.6,
className,
}: AsciiEngineProps) {
const hostRef = useRef<HTMLDivElement>(null);
const canvasRef = useRef<HTMLCanvasElement>(null);
const live = useRef({ shapes, ramp, colors, fontSize, font, speed, depth });
const reset = useRef<(() => void) | null>(null);
// keyed by content, so inline arrays from a parent don't reset the morph every render
const shapesKey = shapes.join();
const colorsKey = colors.join();
useEffect(() => {
live.current = { shapes, ramp, colors, fontSize, font, speed, depth };
});
useEffect(() => {
reset.current?.();
}, [shapesKey, ramp, colorsKey, fontSize, font]);
useEffect(() => {
const host = hostRef.current;
const canvas = canvasRef.current;
if (!host || !canvas) return;
if (getComputedStyle(host).position === "static") host.style.position = "relative";
const ctx = canvas.getContext("2d")!;
const reduced = isReducedMotion();
const meshes: Record<AsciiShape, Mesh> = {
torus: torus(),
knot: knot(),
blob: { p: new Float32Array(N * 3), n: new Float32Array(N * 3) },
};
const s = {
from: 0, to: 0, morph: 1, ax: -0.5, ay: 0.4, vx: 0, vy: 0.6, t: 0,
over: false, lx: 0, ly: 0, cx: -1e4, cy: -1e4, hx: 0, hy: 0, sx: 0, sy: 0, hov: 0,
};
// click shockwaves: centre (css px) and start time
const waves: { x: number; y: number; t0: number }[] = [];
/* ---------- the glyph atlas: every character in every colour, pre-rendered ---------- */
let atlas = document.createElement("canvas");
let cw = 6.6, ch = 11.55, fs = 11, dpr = 1, atlasKey = "";
const palette = () => {
const L = live.current;
return [...L.colors, "rgba(242,240,235,0.22)"]; // last one: faint scanner flicker
};
const fontFamily = () => {
const f = live.current.font;
const m = f.match(/^var\((--[\w-]+)\)/);
return m ? getComputedStyle(document.documentElement).getPropertyValue(m[1]).trim() || "monospace" : f;
};
const buildAtlas = () => {
const L = live.current;
const pal = palette();
const key = [fs, dpr, L.ramp, pal.join(), L.font].join("|");
if (key === atlasKey) return;
atlasKey = key;
atlas = document.createElement("canvas");
atlas.width = Math.ceil(cw * dpr) * L.ramp.length;
atlas.height = Math.ceil(ch * dpr) * pal.length;
const a = atlas.getContext("2d")!;
a.setTransform(dpr, 0, 0, dpr, 0, 0);
a.font = `600 ${fs}px ${fontFamily()}`;
a.textBaseline = "top";
const gw = Math.ceil(cw * dpr) / dpr;
const gh = Math.ceil(ch * dpr) / dpr;
pal.forEach((col, ci) => {
a.fillStyle = col;
for (let gi = 0; gi < L.ramp.length; gi++) a.fillText(L.ramp[gi], gi * gw, ci * gh);
});
};
/* ---------- reusable per-frame buffers ---------- */
let w = 1, h = 1, cols = 1, rows = 1, cells = 1;
let zbuf = new Float32Array(1);
let lum = new Float32Array(1);
let glitch = new Uint8Array(1);
let gchar = new Uint8Array(1);
const resize = () => {
dpr = Math.min(window.devicePixelRatio || 1, 2);
w = Math.max(1, canvas.clientWidth);
h = Math.max(1, canvas.clientHeight);
canvas.width = Math.round(w * dpr);
canvas.height = Math.round(h * dpr);
fs = live.current.fontSize ?? (w < 420 ? 9 : 11);
cw = fs * 0.6;
ch = fs * 1.05;
cols = Math.max(1, Math.floor(w / cw));
rows = Math.max(1, Math.floor(h / ch));
cells = cols * rows;
zbuf = new Float32Array(cells);
lum = new Float32Array(cells);
glitch = new Uint8Array(cells);
gchar = new Uint8Array(cells);
buildAtlas();
};
resize();
reset.current = () => {
resize();
s.from = s.to = 0;
s.morph = 1;
};
/* ---------- input ---------- */
let lastMorph = -10;
const next = () => {
const count = Math.max(1, live.current.shapes.length);
s.from = s.to;
s.to = (s.to + 1) % count;
s.morph = reduced ? 1 : 0;
lastMorph = s.t;
};
const enter = (e: PointerEvent) => {
s.lx = e.clientX;
s.ly = e.clientY;
s.over = true;
if (s.morph >= 1 && s.t - lastMorph > 1.2) next();
};
const move = (e: PointerEvent) => {
const r = canvas.getBoundingClientRect();
s.cx = e.clientX - r.left;
s.cy = e.clientY - r.top;
s.hx = (s.cx / r.width) * 2 - 1;
s.hy = (s.cy / r.height) * 2 - 1;
s.over = true;
const dx = e.clientX - s.lx;
const dy = e.clientY - s.ly;
s.lx = e.clientX;
s.ly = e.clientY;
if (Math.abs(dx) > 80 || Math.abs(dy) > 80) return;
s.vy = Math.max(-9, Math.min(9, s.vy + dx * 0.06));
s.vx = Math.max(-9, Math.min(9, s.vx + dy * 0.06));
};
const leave = () => {
s.over = false;
s.hx = 0;
s.hy = 0;
};
const click = (e: PointerEvent) => {
if (reduced) return;
const r = canvas.getBoundingClientRect();
waves.push({ x: e.clientX - r.left, y: e.clientY - r.top, t0: s.t });
if (waves.length > 4) waves.shift();
if (s.morph >= 1) next();
};
host.addEventListener("pointerenter", enter);
host.addEventListener("pointermove", move);
host.addEventListener("pointerleave", leave);
host.addEventListener("pointerdown", click);
/* ---------- one frame ---------- */
const frame = (dt: number) => {
const L = live.current;
const list = L.shapes.length ? L.shapes : (["torus"] as AsciiShape[]);
s.t += dt;
const pull = Math.min(1, dt * (s.over ? 0.9 : 1.5));
s.vy += ((reduced ? 0 : 0.6 * L.speed) - s.vy) * pull;
s.vx += ((reduced ? 0 : 0.15 * L.speed) - s.vx) * pull;
s.ay += s.vy * dt;
s.ax += s.vx * dt;
if (s.morph < 1) s.morph = Math.min(1, s.morph + dt / 1.4);
s.hov += ((s.over ? 1 : 0) - s.hov) * Math.min(1, dt * 4);
const follow = Math.min(1, dt * 6);
s.sx += (s.hx - s.sx) * follow;
s.sy += (s.hy - s.sy) * follow;
if (list.includes("blob")) blob(meshes.blob, reduced ? 0 : s.t);
zbuf.fill(0);
lum.fill(-2);
glitch.fill(0);
const k = Math.min(cols * 0.42, rows * (ch / cw) * 0.62) * 1.75 * (1 + 0.14 * s.hov);
const A = meshes[list[s.from % list.length]];
const B = meshes[list[s.to % list.length]];
const m = ease(s.morph);
// the model turns to face the pointer while hovered
const rx = s.ax + s.sy * 0.75 * s.hov;
const ry = s.ay + s.sx * 0.95 * s.hov;
const ca = Math.cos(rx), sa = Math.sin(rx), cb = Math.cos(ry), sb = Math.sin(ry);
// light: upper-left by default; follows the cursor when hovered
let Lx = -0.45 + (s.sx * 1.2 + 0.45) * s.hov;
let Ly = 0.6 + (-s.sy * 1.2 - 0.6) * s.hov;
let Lz = -0.66 + (-0.75 + 0.66) * s.hov;
const Ll = Math.hypot(Lx, Ly, Lz) || 1;
Lx /= Ll;
Ly /= Ll;
Lz /= Ll;
for (let i = 0; i < N; i++) {
const q = i * 3;
let x = A.p[q] + (B.p[q] - A.p[q]) * m;
let y = A.p[q + 1] + (B.p[q + 1] - A.p[q + 1]) * m;
let z = A.p[q + 2] + (B.p[q + 2] - A.p[q + 2]) * m;
let nx = A.n[q] + (B.n[q] - A.n[q]) * m;
let ny = A.n[q + 1] + (B.n[q + 1] - A.n[q + 1]) * m;
let nz = A.n[q + 2] + (B.n[q + 2] - A.n[q + 2]) * m;
let t1 = x * cb + z * sb;
z = -x * sb + z * cb;
x = t1;
t1 = y * ca - z * sa;
z = y * sa + z * ca;
y = t1;
let n1 = nx * cb + nz * sb;
nz = -nx * sb + nz * cb;
nx = n1;
n1 = ny * ca - nz * sa;
nz = ny * sa + nz * ca;
ny = n1;
const ooz = 1 / (z + 4);
const px = Math.floor(cols / 2 + x * k * ooz);
// centre sits a little high so a caption never covers the model
const py = Math.floor(rows * 0.42 - y * k * ooz * (cw / ch));
if (px < 0 || px >= cols || py < 0 || py >= rows) continue;
const c = py * cols + px;
if (ooz > zbuf[c]) {
zbuf[c] = ooz;
const nl = Math.hypot(nx, ny, nz) || 1;
let l = (nx * Lx + ny * Ly + nz * Lz) / nl;
// depth: only the far half of the model recedes toward lighter glyphs;
// the front stays at full strength (ooz 0.25 = the model's centre plane)
const near = Math.min(1, Math.max(0, (ooz - 0.18) / 0.07));
l = l - (1 - near) * 0.45 * L.depth;
lum[c] = Math.max(-1, l);
}
}
const ox = (w - cols * cw) / 2;
const oy = (h - rows * ch) / 2;
// glitch halo under the cursor
if (s.hov > 0.05 && !reduced) {
const R = Math.max(60, w * 0.11);
const c0 = Math.max(0, Math.floor((s.cx - ox - R) / cw));
const c1 = Math.min(cols - 1, Math.ceil((s.cx - ox + R) / cw));
const r0 = Math.max(0, Math.floor((s.cy - oy - R) / ch));
const r1 = Math.min(rows - 1, Math.ceil((s.cy - oy + R) / ch));
for (let yy = r0; yy <= r1; yy++)
for (let xx = c0; xx <= c1; xx++) {
const d = Math.hypot(ox + (xx + 0.5) * cw - s.cx, oy + (yy + 0.5) * ch - s.cy);
const near = (1 - d / R) * s.hov;
if (near <= 0) continue;
const c = yy * cols + xx;
if (lum[c] > -1.5) {
lum[c] = Math.min(1, lum[c] + near * 0.6);
if (Math.random() < near * 0.55) {
glitch[c] = Math.random() < 0.55 ? 4 : 2; // hot or body colour
gchar[c] = Math.floor(Math.random() * L.ramp.length);
}
} else if (Math.random() < near * 0.12) {
glitch[c] = 5;
gchar[c] = Math.floor(Math.random() * L.ramp.length);
}
}
}
// click shockwaves: an expanding ring of glyph noise
for (let wi = waves.length - 1; wi >= 0; wi--) {
const wv = waves[wi];
const age = s.t - wv.t0;
const radius = age * Math.max(w, h) * 0.9;
const life = 1 - age / 1.1;
if (life <= 0) {
waves.splice(wi, 1);
continue;
}
const band = 26;
const c0 = Math.max(0, Math.floor((wv.x - ox - radius - band) / cw));
const c1 = Math.min(cols - 1, Math.ceil((wv.x - ox + radius + band) / cw));
const r0 = Math.max(0, Math.floor((wv.y - oy - radius - band) / ch));
const r1 = Math.min(rows - 1, Math.ceil((wv.y - oy + radius + band) / ch));
for (let yy = r0; yy <= r1; yy++)
for (let xx = c0; xx <= c1; xx++) {
const d = Math.hypot(ox + (xx + 0.5) * cw - wv.x, oy + (yy + 0.5) * ch - wv.y);
const on = 1 - Math.abs(d - radius) / band;
if (on <= 0 || Math.random() > on * life * 0.9) continue;
const c = yy * cols + xx;
glitch[c] = lum[c] > -1.5 ? (Math.random() < 0.5 ? 4 : 2) : 5;
gchar[c] = Math.floor(Math.random() * L.ramp.length);
}
}
/* ---------- draw from the atlas ---------- */
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, w, h);
const n = L.ramp.length;
const gw = Math.ceil(cw * dpr);
const gh = Math.ceil(ch * dpr);
const morphing = s.morph < 1;
const noise = morphing && !reduced ? 0.18 * Math.sin(Math.PI * s.morph) : 0;
for (let c = 0; c < cells; c++) {
let ci: number;
let gi: number;
if (glitch[c]) {
ci = glitch[c] - 1;
gi = gchar[c];
} else {
const l = lum[c];
if (l < -1.5) continue;
ci = l < 0.15 ? 0 : l < 0.6 ? 1 : l < 0.965 ? 2 : 3;
gi = Math.max(0, Math.min(n - 1, Math.floor(((l + 1) / 2) * n)));
// glyph noise while morphing
if (noise && Math.random() < noise) gi = Math.floor(Math.random() * n);
}
ctx.drawImage(atlas, gi * gw, ci * gh, gw, gh, ox + (c % cols) * cw, oy + Math.floor(c / cols) * ch, gw / dpr, gh / dpr);
}
};
/* ---------- loop ---------- */
let raf = 0;
let last = 0;
let visible = false;
const loop = (now: number) => {
raf = requestAnimationFrame(loop);
const dt = last ? Math.min(0.05, (now - last) / 1000) : 1 / 60;
last = now;
frame(dt);
};
const sync = () => {
const run = visible && !document.hidden;
if (run && !raf) {
last = 0;
raf = requestAnimationFrame(loop);
} else if (!run && raf) {
cancelAnimationFrame(raf);
raf = 0;
}
};
const io = new IntersectionObserver(([e]) => {
visible = e.isIntersecting;
sync();
});
io.observe(host);
document.addEventListener("visibilitychange", sync);
let lastW = canvas.clientWidth;
let lastH = canvas.clientHeight;
const ro = new ResizeObserver(() => {
if (Math.abs(canvas.clientWidth - lastW) > 2 || Math.abs(canvas.clientHeight - lastH) > 2) {
lastW = canvas.clientWidth;
lastH = canvas.clientHeight;
resize();
}
});
ro.observe(canvas);
document.fonts?.ready.then(() => {
atlasKey = "";
buildAtlas();
});
return () => {
reset.current = null;
cancelAnimationFrame(raf);
io.disconnect();
ro.disconnect();
document.removeEventListener("visibilitychange", sync);
host.removeEventListener("pointerenter", enter);
host.removeEventListener("pointermove", move);
host.removeEventListener("pointerleave", leave);
host.removeEventListener("pointerdown", click);
};
}, []);
return (
<div
ref={hostRef}
role="img"
aria-label={`A 3D ${shapes.join(", then ")} drawn in text characters`}
className={["ascii-engine", className].filter(Boolean).join(" ")}
>
<canvas ref={canvasRef} aria-hidden="true" style={{ position: "absolute", inset: 0, width: "100%", height: "100%", display: "block" }} />
</div>
);
}
components/inreact/ascii-engine.css
.ascii-engine {
overflow: hidden;
}
One prompt, any AI agent
Paste into Claude Code, Codex, Cursor or Windsurf. It carries your tweaks and the full source, so the agent installs it exactly.
Props
8 propsshapes("torus" | "knot" | "blob")[]Shapes to morph between, in order.default ["torus", "knot", "blob"]default ["torus", "knot", "blob"]rampstringCharacters from darkest to brightest.default ".,-~:;=!*#$@"default ".,-~:;=!*#$@"colors[string, string, string, string]Shadow, body, highlight and hot-spot colours.default dim chalk, blue, chalk, signaldefault dim chalk, blue, chalk, signalfontSizenumberCharacter size in px.default 11 (9 on small screens)default 11 (9 on small screens)fontstringMonospace font family for the glyphs (a CSS var() works too).default system monospacedefault system monospacespeednumberIdle spin speed multiplier.default 1default 1depthnumberHow much the far side fades toward lighter glyphs. 0 turns it off.default 0.6default 0.6classNamestringSize it, e.g. h-[420px] w-full.