Sparks near your pointer glitter. Click to send a shell to that spot.
Live code
As tuned above.
Every control in the inspector updates this snippet directly. Defaults are omitted to keep your markup minimal.
hero.tsx
import { AsciiFireworks } from '@/components/lilt/ascii/more-scenes/ascii-fireworks';
export function Hero() {
return (
<section style={{ height: 560, background: '#07070a', color: '#e8e8ee' }}>
<AsciiFireworks />
</section>
);
}
Installation8
Source you own.
This is source, not a package: the shadcn CLI copies it into your project with the shared pieces it needs. Its only dependency is React.
npx shadcn@latest add https://liltui.vercel.app/r/fireworks.jsoncomponents/lilt/ascii/more-scenes/ascii-fireworks.tsx
ascii-fireworks.tsx
'use client';
import { AsciiCanvas, useSceneProps, type SceneProps } from '../react/ascii-canvas';
import { createFireworks, type FireworksOptions } from './fireworks';
/** Fireworks over a city at night: peonies, rings and willows that fall, fade and smoke. */
export function AsciiFireworks(props: SceneProps<FireworksOptions>) {
return <AsciiCanvas {...useSceneProps(props, createFireworks)} />;
}
components/lilt/ascii/more-scenes/fireworks.ts
fireworks.ts
import { stroke } from '../engine/glyphs';
import { clamp, hash3, noise3 } from '../engine/noise';
import { DOT, type GlyphSurface } from '../engine/surface';
import type { AsciiGrid, AsciiPointer, AsciiScene } from '../engine/types';
export interface FireworksOptions {
/** Colours the shells burst in. Default violet, rose, gold and sky blue. */
colors?: readonly string[];
/** Shells launched a second, on average. Default 0.55. */
rate?: number;
/** A low city skyline along the bottom, with lit windows. Default true. */
skyline?: boolean;
}
const DEFAULT_COLORS = ['#8b6cff', '#e5489c', '#f5a93c', '#4fb6f0'] as const;
const INK = 0;
/** Smoke: a soft grey-violet that shows on night and paper alike. */
const SMOKE = 2;
/** Glitter and crackle: a hot gold that shows on both backdrops. */
const GLINT = 3;
/** The city's silhouette. */
const CITY = 4;
/** Lit windows in the skyline: a warm lamp colour. */
const WINDOW = 1;
/** The burst colours start here. */
const FIRST = 5;
/** Gravity and how fast sparks lose speed, in square units (cell widths) and seconds. */
const GRAVITY = 7;
const TRAIL = 12;
type Kind = 'peony' | 'ring' | 'willow' | 'double' | 'palm';
const KINDS: Kind[] = ['peony', 'ring', 'peony', 'willow', 'double', 'palm', 'peony', 'ring'];
interface Shell {
x: number;
y: number;
vx: number;
vy: number;
tone: number;
kind: Kind;
/** Remembers where it has been, for the faint rising trail. */
trail: Float32Array;
tick: number;
}
interface Spark {
x: number;
y: number;
vx: number;
vy: number;
age: number;
life: number;
tone: number;
drag: number;
/** Positions the spark has passed through, newest first: its trail. */
trail: Float32Array;
filled: number;
/** How many trail points are drawn. Willows draw long trails, crackles none. */
length: number;
/** Bursts into a few short white stars as it dies. */
crackle: boolean;
/** Tiny short-lived stars from a crackle. */
tiny: boolean;
seed: number;
}
interface Flash {
x: number;
y: number;
tone: number;
age: number;
radius: number;
}
/**
* Fireworks over a city at night. Shells rise on a faint trail and burst into clean shapes: round
* peonies, tilted rings, drooping golden willows, palms and two-colour doubles. Each spark is a
* bright head with a short trail drawn along its path; it slows, falls, flickers and fades, and
* the bursts leave smoke that drifts on the wind, lit for a moment by the next one. Some shells
* crackle as they die. A click sends a shell to burst where you clicked; sparks near the pointer
* glitter.
*/
export function createFireworks(options: FireworksOptions = {}): AsciiScene {
const colors = options.colors?.length ? options.colors : DEFAULT_COLORS;
const rate = Math.max(0, options.rate ?? 0.55);
const skyline = options.skyline ?? true;
let grid: AsciiGrid = { cols: 0, rows: 0, aspect: 2 };
let width = 0;
let height = 0;
let smoke = new Float32Array(0);
let spare = new Float32Array(0);
/** Top row of the skyline in each column, or the row count where there is none. */
let roof = new Int16Array(0);
const shells: Shell[] = [];
const sparks: Spark[] = [];
const flashes: Flash[] = [];
let time = 0;
let owed = 0;
let launches = 0;
let wind = 0;
let drift = 0;
let smokeTick = 0;
let px = 0;
let py = 0;
let pointerOn = false;
const size = () => Math.min(width, height * 1.25);
function buildSkyline() {
roof = new Int16Array(grid.cols).fill(grid.rows);
if (!skyline) return;
const { cols, rows } = grid;
const tall = Math.max(2, Math.round(rows * 0.13));
let col = 0;
let k = 0;
while (col < cols) {
const w = 3 + Math.floor(hash3(k, 1, 31) * 9);
// Lower toward the middle, so the sky over the centre stays open.
const mid = Math.abs(col + w / 2 - cols / 2) / (cols / 2);
const h = Math.round(1 + hash3(k, 2, 31) * tall * (0.45 + 0.55 * mid));
for (let c = col; c < Math.min(cols, col + w); c++) roof[c] = rows - h;
col += w + (hash3(k, 3, 31) < 0.3 ? 1 : 0);
k++;
}
}
function launch(x: number, apexY: number, kind?: Kind) {
const tone = FIRST + (launches % colors.length);
const chosen = kind ?? KINDS[Math.floor(hash3(launches, 7, 3) * KINDS.length)]!;
launches++;
const rise = Math.max(4, height - apexY);
shells.push({
x,
y: height,
vx: (Math.random() - 0.5) * 1.5,
vy: -Math.sqrt(2 * GRAVITY * 3 * rise),
tone,
kind: chosen,
trail: new Float32Array(TRAIL * 2).fill(-1),
tick: 0,
});
}
function autoLaunch() {
const x = width * (0.18 + 0.64 * Math.random());
const apex = height * (0.3 + 0.2 * Math.random());
launch(x, apex);
}
function spark(
x: number,
y: number,
vx: number,
vy: number,
tone: number,
life: number,
drag: number,
length: number,
): Spark {
const s: Spark = {
x,
y,
vx,
vy,
age: 0,
life,
tone,
drag,
trail: new Float32Array(TRAIL * 2).fill(Number.NaN),
filled: 0,
length,
crackle: false,
tiny: false,
seed: Math.random() * 1000,
};
sparks.push(s);
return s;
}
function burst(shell: Shell) {
const { x, y, tone, kind } = shell;
const s = size();
// Initial speed for a burst of radius `r`: with drag k a spark coasts about v / k.
const speedFor = (r: number, drag: number) => r * drag;
const other = FIRST + ((tone - FIRST + 1 + Math.floor(Math.random() * 2)) % colors.length);
const crackles = Math.random() < 0.35;
flashes.push({ x, y, tone, age: 0, radius: s * 0.22 });
if (kind === 'ring') {
const n = 40;
const tilt = 0.35 + Math.random() * 0.55;
const turn = Math.random() * Math.PI;
const v = speedFor(s * 0.2, 1.7);
for (let i = 0; i < n; i++) {
const a = (i / n) * Math.PI * 2;
const ox = Math.cos(a);
const oy = Math.sin(a) * tilt;
const rx = ox * Math.cos(turn) - oy * Math.sin(turn);
const ry = ox * Math.sin(turn) + oy * Math.cos(turn);
spark(x, y, rx * v, ry * v, tone, 1.7 + Math.random() * 0.3, 1.7, 4);
}
return;
}
if (kind === 'palm') {
// A few thick fronds that arch over and droop.
const n = 9;
const v = speedFor(s * 0.2, 1.4);
for (let i = 0; i < n; i++) {
const a = -Math.PI / 2 + ((i / (n - 1)) * 2 - 1) * 1.45 + (Math.random() - 0.5) * 0.15;
for (let j = 0; j < 3; j++) {
const f = 1 - j * 0.12;
spark(
x,
y,
Math.cos(a) * v * f,
Math.sin(a) * v * f,
j === 0 ? tone : other,
2.4,
1.4,
7,
);
}
}
return;
}
const willow = kind === 'willow';
const n = willow ? 46 : 52;
const drag = willow ? 2.6 : 1.6;
const v = speedFor(s * (willow ? 0.2 : 0.21), drag);
// Gold for willows whatever the colour: that is what willows are.
const head = willow ? FIRST + Math.min(2, colors.length - 1) : tone;
for (let i = 0; i < n; i++) {
// Even directions over the outer band of a sphere seen from the side. The stars heading
// toward or away from you would crowd the middle, so the shell is left as a clean ball.
const z = (1 - (2 * (i + 0.5)) / n) * 0.8;
const r = Math.sqrt(1 - z * z);
const a = i * 2.39996 + Math.random() * 0.05;
const jitter = 0.95 + Math.random() * 0.1;
const sp = spark(
x,
y,
Math.cos(a) * r * v * jitter,
Math.sin(a) * r * v * jitter,
head,
willow ? 3.2 + Math.random() * 0.8 : 1.9 + Math.random() * 0.4,
drag,
willow ? 7 : 4,
);
sp.crackle = crackles && !willow && Math.random() < 0.6;
}
if (kind === 'double') {
// A ring of a second colour inside the ball.
const inner = 20;
const vi = v * 0.45;
for (let i = 0; i < inner; i++) {
const a = (i / inner) * Math.PI * 2;
spark(x, y, Math.cos(a) * vi, Math.sin(a) * vi, other, 1.7, drag, 3);
}
}
// A puff of smoke where the shell broke.
puff(x, y, 1.6);
}
function puff(x: number, y: number, amount: number) {
const { cols, rows, aspect } = grid;
const r = 3;
const cx = Math.floor(x);
const cy = Math.floor(y / aspect);
for (let row = cy - 2; row <= cy + 2; row++) {
for (let col = cx - r * 2; col <= cx + r * 2; col++) {
if (col < 0 || row < 0 || col >= cols || row >= rows) continue;
const d = Math.hypot((col - cx) / (r * 2), (row - cy) / 2);
if (d < 1) smoke[row * cols + col]! += amount * 0.25 * (1 - d);
}
}
}
function stepSmoke() {
// Smoke spreads a little, thins, rises a touch and drifts with the wind.
const { cols, rows } = grid;
drift += wind * (1 / 15);
const shift = Math.trunc(drift);
drift -= shift;
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
const from = col - shift;
const i = row * cols + col;
if (from < 1 || from >= cols - 1) {
spare[i] = 0;
continue;
}
const j = row * cols + from;
const below = row < rows - 1 ? smoke[j + cols]! : 0;
const above = row > 0 ? smoke[j - cols]! : 0;
const v =
smoke[j]! * 0.6 + (smoke[j - 1]! + smoke[j + 1]!) * 0.14 + below * 0.08 + above * 0.04;
spare[i] = v * 0.985;
}
}
[smoke, spare] = [spare, smoke];
}
function record(trail: Float32Array, x: number, y: number) {
trail.copyWithin(2, 0, trail.length - 2);
trail[0] = x;
trail[1] = y;
}
const scene: AsciiScene = {
palette: ['ink', '#ffcf7a', '#8d86a0', '#f0a93a', '#1d1a2e', ...colors],
lineHeight: 1,
settle: 0.4,
resize(next) {
const same =
next.cols === grid.cols && next.rows === grid.rows && next.aspect === grid.aspect;
grid = next;
if (same && width) return;
width = grid.cols;
height = grid.rows * grid.aspect;
smoke = new Float32Array(grid.cols * grid.rows);
spare = new Float32Array(grid.cols * grid.rows);
shells.length = 0;
sparks.length = 0;
flashes.length = 0;
buildSkyline();
// Open with a shell already on its way, so the first frame is not an empty sky.
launch(width * 0.42, height * 0.36, 'peony');
owed = -0.6;
// Run it up to the moment the first shell is in bloom, so even a still frame has a burst.
const idle = { x: 0, y: 0, active: false };
for (let t = 0; t < 1.9; t += 1 / 60) scene.step(1 / 60, idle);
},
step(dt, pointer: AsciiPointer) {
if (!grid.cols) return;
time += dt;
wind = 1.4 + (noise3(time * 0.05, 0, 3) - 0.5) * 3;
pointerOn = pointer.active;
px = pointer.x;
py = pointer.y * grid.aspect;
owed += dt * rate;
while (owed >= 1) {
owed -= 1 + (Math.random() - 0.5) * 0.6;
autoLaunch();
}
for (let i = shells.length - 1; i >= 0; i--) {
const sh = shells[i]!;
sh.vy += GRAVITY * 3 * dt;
sh.x += sh.vx * dt;
sh.y += sh.vy * dt;
if (++sh.tick % 2 === 0) record(sh.trail, sh.x, sh.y);
if (sh.vy > -1.5) {
shells.splice(i, 1);
burst(sh);
}
}
for (let i = sparks.length - 1; i >= 0; i--) {
const s = sparks[i]!;
s.age += dt;
if (s.age > s.life || s.y > height + 2) {
sparks.splice(i, 1);
if (s.crackle && !s.tiny) {
for (let k = 0; k < 3; k++) {
const a = Math.random() * Math.PI * 2;
const t = spark(
s.x,
s.y,
Math.cos(a) * 3,
Math.sin(a) * 3,
GLINT,
0.25 + Math.random() * 0.2,
4,
0,
);
t.tiny = true;
}
}
continue;
}
const k = Math.exp(-s.drag * dt);
s.vx = s.vx * k + wind * 0.12 * dt;
s.vy = s.vy * k + GRAVITY * dt * (s.age / s.life + 0.25);
s.x += s.vx * dt;
s.y += s.vy * dt;
// Trail points: every step for most, every fourth for a willow's long arc.
if (Math.round(s.age * 60) % (s.length > 4 ? 4 : 2) === 0) {
record(s.trail, s.x, s.y);
s.filled = Math.min(TRAIL, s.filled + 1);
}
if (s.age > s.life * 0.5 && !s.tiny && Math.random() < dt * 4) {
const col = Math.floor(s.x);
const row = Math.floor(s.y / grid.aspect);
if (col >= 0 && row >= 0 && col < grid.cols && row < grid.rows) {
smoke[row * grid.cols + col]! += 0.05;
}
}
}
for (let i = flashes.length - 1; i >= 0; i--) {
flashes[i]!.age += dt;
if (flashes[i]!.age > 0.9) flashes.splice(i, 1);
}
smokeTick += dt;
while (smokeTick >= 1 / 15) {
smokeTick -= 1 / 15;
stepSmoke();
}
},
press(x, y) {
const apex = clamp(y * grid.aspect, height * 0.08, height * 0.8);
launch(clamp(x, 2, width - 2), apex);
// A clicked shell flies straight up to the point.
shells[shells.length - 1]!.vx = 0;
},
draw(surface: GlyphSurface) {
const { cols, rows, aspect } = grid;
if (!cols) return;
const flash = flashes.length ? flashes[flashes.length - 1]! : null;
// Stars: sparse and still, dimmer toward the city's glow.
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
if (row >= roof[col]!) continue;
const i = row * cols + col;
const m = smoke[i]!;
if (m > 0.02) {
// Smoke, faint and soft. A fresh burst lights the smoke near it in its own colour.
let tone = SMOKE;
let lit = 0;
if (flash) {
const d =
Math.hypot(col - flash.x, (row + 0.5) * aspect - flash.y) / (flash.radius * 1.6);
lit = clamp(1 - d, 0, 1) * clamp(1 - flash.age / 0.9, 0, 1);
if (lit > 0.25) tone = flash.tone;
}
// Dithered rather than shaded, so it reads as haze and not as a grid.
if (hash3(col, row, Math.floor(time * 2)) < clamp(m * 1.5, 0, 0.6)) {
surface.put(col, row, DOT, tone, 0.18 + clamp(m * 0.25, 0, 0.12) + lit * 0.3);
continue;
}
}
const h = hash3(col, row, 11);
if (h < 0.012 && row < rows * 0.75) {
const twinkle = 0.5 + 0.5 * Math.sin(time * (0.6 + h * 60) + h * 500);
surface.put(col, row, DOT, INK, 0.1 + 0.22 * twinkle);
}
}
}
// The first moment of a burst: a soft round glow of faint blocks around its heart.
for (const f of flashes) {
const life = clamp(1 - f.age / 0.45, 0, 1);
if (life <= 0) continue;
const r = f.radius * (0.2 + 0.3 * (f.age / 0.45));
const r0 = Math.floor((f.y - r) / aspect);
const r1 = Math.ceil((f.y + r) / aspect);
for (let row = r0; row <= r1; row++) {
for (let col = Math.floor(f.x - r); col <= Math.ceil(f.x + r); col++) {
const d = Math.hypot(col + 0.5 - f.x, (row + 0.5) * aspect - f.y) / r;
if (d > 1) continue;
surface.fill(col, row, f.tone, life * (1 - d) * (1 - d) * 0.35);
}
}
}
for (const sh of shells) {
for (let k = TRAIL - 1; k >= 0; k--) {
const tx = sh.trail[k * 2]!;
const ty = sh.trail[k * 2 + 1]!;
if (tx < 0) continue;
surface.put(tx, ty / aspect, DOT, sh.tone, 0.45 * (1 - k / TRAIL));
}
surface.fill(sh.x, sh.y / aspect, sh.tone, 0.9);
}
for (const s of sparks) if (!s.tiny) drawTrail(surface, s);
for (const s of sparks) drawHead(surface, s);
if (skyline) drawSkyline(surface);
},
};
return scene;
/** How bright a spark is now: bright, then a slow fade, flickering as it burns out. */
function brightness(s: Spark) {
const t = s.age / s.life;
let alpha = t < 0.6 ? 1 : 1 - (t - 0.6) / 0.4;
if (t > 0.55 && hash3(Math.floor(s.age * 18), Math.floor(s.seed), 5) < 0.35) alpha *= 0.3;
return alpha;
}
/**
* The trail: a short tail walked back along the spark's path. Only the cell behind the head is a
* stroke, to show the way it flies; the rest are fading dots.
*/
function drawTrail(surface: GlyphSurface, s: Spark) {
const { aspect } = grid;
const alpha = brightness(s);
const speed = Math.hypot(s.vx, s.vy);
const reach = s.length > 4 ? 6 : clamp(1 + speed * 0.09, 1, 3.5);
let ax = s.x;
let ay = s.y;
let walked = 0;
let first = true;
for (let k = 0; k < s.filled && walked < reach; k++) {
const bx = s.trail[k * 2]!;
const by = s.trail[k * 2 + 1]!;
if (Number.isNaN(bx)) break;
const dx = bx - ax;
const dy = (by - ay) / aspect;
const len = Math.hypot(dx, dy);
if (len < 1e-3) continue;
for (let u = walked === 0 ? 1 : 0; u < len && walked + u < reach; u += 1) {
const f = 1 - (walked + u) / (reach + 0.5);
const g = first && speed > 6 ? stroke(dx, by - ay) : DOT;
first = false;
surface.put(ax + (dx / len) * u, ay / aspect + (dy / len) * u, g, s.tone, f * alpha * 0.7);
}
walked += len;
ax = bx;
ay = by;
}
}
/** The head: a bright block of colour, glittering gold near the pointer. */
function drawHead(surface: GlyphSurface, s: Spark) {
const t = s.age / s.life;
const alpha = brightness(s);
const col = s.x;
const row = s.y / grid.aspect;
if (s.tiny) {
surface.put(col, row, t < 0.5 ? '+' : DOT, GLINT, alpha);
return;
}
const glitter =
pointerOn &&
Math.hypot(s.x - px, s.y - py) < 10 &&
hash3(Math.floor(time * 20), Math.floor(s.seed), 9) < 0.5;
if (glitter) {
surface.fill(col, row, GLINT, 0.95);
surface.put(col, row, '+', CITY, 0.6);
return;
}
// Young sparks burn as solid blocks; dying ones shrink to a point.
if (t < 0.7) surface.fill(col, row, s.tone, alpha * (t < 0.15 ? 1 : 0.85));
else surface.put(col, row, DOT, s.tone, alpha);
}
function drawSkyline(surface: GlyphSurface) {
const { cols, rows } = grid;
for (let col = 0; col < cols; col++) {
const top = roof[col]!;
const left = col > 0 ? roof[col - 1]! : rows;
const right = col < cols - 1 ? roof[col + 1]! : rows;
for (let row = top; row < rows; row++) {
// Solid silhouettes, one dark block a cell, and lit windows in rows.
surface.fill(col, row, CITY, 0.92);
const inside = row > top && row < rows - 1 && left <= top && right <= top;
if (inside && col % 2 === 1 && (row - top) % 2 === 1) {
const h = hash3(col, row, 61);
const on = h < 0.3 && noise3(col * 0.3, row, time * 0.05 + h * 9) > 0.35;
if (on) surface.put(col, row, DOT, WINDOW, 0.55 + 0.4 * h);
}
}
}
}
}
components/lilt/ascii/engine/stage.tsascii-canvas
stage.ts
import { GlyphSurface, LEVELS } from './surface';
import type { AsciiPointer, AsciiScene } from './types';
const STEP = 1 / 60;
const MAX_STEPS = 8;
const FALLBACK_FONT = 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace';
export interface AsciiStageOptions {
/** Font size of each cell in CSS pixels. Smaller cells give finer pictures. Default 14. */
cellSize?: number;
/** Follow the pointer and answer clicks. Default true. */
interactive?: boolean;
/** How fast the scene's clock runs: 0.5 is half speed, 2 is double. Default 1. */
speed?: number;
}
/**
* Runs a scene on a canvas: a fixed-step clock, resizing, pointer input, pausing while off screen
* or in a hidden tab, a single still frame for reduced motion, and repainting when the font or the
* page theme changes. The canvas's CSS `font-family` and `color` set the type and the ink.
*/
export class AsciiStage {
private ctx: CanvasRenderingContext2D;
private surface = new GlyphSurface();
private styles: string[] = [];
private pointer: AsciiPointer = { x: 0, y: 0, active: false };
private cellSize: number;
private interactive: boolean;
private speed: number;
private font = '';
private cw = 8;
/** Whether every glyph advances one cell, so rows can be painted as strings. */
private mono = true;
private ch = 18;
private raf = 0;
private last = 0;
private acc = 0;
private time = 0;
private onScreen = true;
private disposed = false;
private reducedMotion: MediaQueryList;
private resizeObserver: ResizeObserver;
/** The grid the scene was last sized to. */
private grid = '';
private intersectionObserver: IntersectionObserver;
private themeObserver: MutationObserver;
constructor(
private canvas: HTMLCanvasElement,
private scene: AsciiScene,
options: AsciiStageOptions = {},
) {
const ctx = canvas.getContext('2d');
if (!ctx) throw new Error('AsciiStage needs a 2D canvas context.');
this.ctx = ctx;
this.cellSize = options.cellSize ?? 14;
this.interactive = options.interactive ?? true;
this.speed = options.speed ?? 1;
this.reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)');
this.resizeObserver = new ResizeObserver(() => this.resize());
this.resizeObserver.observe(canvas);
this.intersectionObserver = new IntersectionObserver(([entry]) => {
this.onScreen = entry?.isIntersecting ?? true;
this.schedule();
});
this.intersectionObserver.observe(canvas);
// Theme switches usually flip a class or attribute on the root; the ink follows.
this.themeObserver = new MutationObserver(() => this.restyle());
this.themeObserver.observe(document.documentElement, {
attributes: true,
attributeFilter: ['class', 'style', 'data-theme'],
});
this.reducedMotion.addEventListener('change', this.schedule);
document.addEventListener('visibilitychange', this.schedule);
window.addEventListener('pointermove', this.onPointerMove, { passive: true });
window.addEventListener('pointerdown', this.onPointerDown, { passive: true });
document.documentElement.addEventListener('pointerleave', this.onPointerLeave);
window.addEventListener('blur', this.onPointerLeave);
this.resize();
// Canvas text never asks for a webfont, so measure again once the page's fonts arrive.
document.fonts?.ready.then(() => {
if (this.disposed) return;
this.resize();
});
this.schedule();
}
destroy() {
this.disposed = true;
cancelAnimationFrame(this.raf);
this.resizeObserver.disconnect();
this.intersectionObserver.disconnect();
this.themeObserver.disconnect();
this.reducedMotion.removeEventListener('change', this.schedule);
document.removeEventListener('visibilitychange', this.schedule);
window.removeEventListener('pointermove', this.onPointerMove);
window.removeEventListener('pointerdown', this.onPointerDown);
document.documentElement.removeEventListener('pointerleave', this.onPointerLeave);
window.removeEventListener('blur', this.onPointerLeave);
}
/** Changes the stage's options in place, keeping the scene's world as it is. */
configure(options: AsciiStageOptions) {
this.speed = options.speed ?? this.speed;
if (options.interactive !== undefined) {
this.interactive = options.interactive;
if (!this.interactive) this.pointer.active = false;
}
if (options.cellSize !== undefined && options.cellSize !== this.cellSize) {
this.cellSize = options.cellSize;
this.resize();
}
}
/** Reads the canvas's `color` again, after the ink was changed by something other than a theme. */
refresh() {
this.restyle();
}
private get still() {
return this.reducedMotion.matches;
}
private resize() {
const rect = this.canvas.getBoundingClientRect();
if (rect.width < 1 || rect.height < 1) return;
const dpr = Math.min(window.devicePixelRatio || 1, 2);
this.canvas.width = Math.round(rect.width * dpr);
this.canvas.height = Math.round(rect.height * dpr);
const family = getComputedStyle(this.canvas).fontFamily || FALLBACK_FONT;
this.font = `500 ${this.cellSize}px ${family}, ${FALLBACK_FONT}`;
const { ctx } = this;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.font = this.font;
this.cw = Math.max(4, ctx.measureText('M').width);
this.mono = Math.abs(ctx.measureText('i').width - this.cw) < 0.01;
this.ch = Math.round(this.cellSize * (this.scene.lineHeight ?? 1.25));
const cols = Math.ceil(rect.width / this.cw);
const rows = Math.ceil(rect.height / this.ch);
this.surface.resize(cols, rows);
// Fonts arriving or a pixel of layout can measure the same grid again; the scene keeps its world.
const grid = `${cols}x${rows}x${this.ch / this.cw}`;
if (grid !== this.grid) {
this.grid = grid;
this.scene.resize({ cols, rows, aspect: this.ch / this.cw });
}
this.restyle();
}
/** Resolves the palette to fill styles, one per colour and opacity step. */
private restyle() {
const { ctx } = this;
const ink = getComputedStyle(this.canvas).color;
this.styles = this.scene.palette.flatMap((colour) => {
ctx.fillStyle = '#000';
ctx.fillStyle = colour === 'ink' ? ink : colour;
const [r, g, b] = parseColour(String(ctx.fillStyle));
return Array.from({ length: LEVELS }, (_, i) => `rgba(${r},${g},${b},${(i + 1) / LEVELS})`);
});
if (this.still) this.drawStill();
}
private schedule = () => {
cancelAnimationFrame(this.raf);
if (this.disposed) return;
if (this.still) {
this.drawStill();
return;
}
if (!this.onScreen || document.hidden) return;
this.last = performance.now();
this.raf = requestAnimationFrame(this.frame);
};
private frame = (now: number) => {
const dt = Math.min(0.1, (now - this.last) / 1000) * this.speed;
this.last = now;
this.acc += dt;
let steps = 0;
while (this.acc >= STEP && steps < MAX_STEPS) {
this.scene.step(STEP, this.pointer);
this.time += STEP;
this.acc -= STEP;
steps++;
}
if (steps === MAX_STEPS) this.acc = 0;
this.paint();
this.raf = requestAnimationFrame(this.frame);
};
/** Lets the scene settle without the pointer, then shows that one frame. */
private drawStill() {
const settle = this.scene.settle ?? 3;
const idle: AsciiPointer = { x: 0, y: 0, active: false };
while (this.time < settle) {
this.scene.step(STEP, idle);
this.time += STEP;
}
this.paint();
}
private paint() {
const { ctx, canvas, surface } = this;
ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.restore();
ctx.font = this.font;
ctx.textBaseline = 'middle';
surface.clear();
this.scene.draw(surface);
surface.paint(ctx, this.styles, this.cw, this.ch, this.mono);
}
private toCells(e: PointerEvent) {
const rect = this.canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
const inside = x >= 0 && y >= 0 && x <= rect.width && y <= rect.height;
return { x: x / this.cw, y: y / this.ch, inside };
}
private onPointerMove = (e: PointerEvent) => {
if (!this.interactive) return;
const { x, y, inside } = this.toCells(e);
this.pointer.x = x;
this.pointer.y = y;
// A finger has no hover; it only presses.
this.pointer.active = inside && e.pointerType !== 'touch';
};
private onPointerDown = (e: PointerEvent) => {
const { x, y, inside } = this.toCells(e);
if (!inside || this.still || !this.interactive) return;
this.scene.press?.(x, y);
};
private onPointerLeave = () => {
this.pointer.active = false;
};
}
/** Reads the `#rrggbb` or `rgba(r, g, b, a)` a canvas reports back for any CSS colour. */
function parseColour(value: string): [number, number, number] {
if (value.startsWith('#')) {
const n = parseInt(value.slice(1, 7), 16);
return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
}
const parts = value.match(/[\d.]+/g)?.map(Number) ?? [];
return [parts[0] ?? 0, parts[1] ?? 0, parts[2] ?? 0];
}
components/lilt/ascii/react/ascii-canvas.tsxascii-canvas
ascii-canvas.tsx
'use client';
import { useEffect, useRef, type CSSProperties } from 'react';
import { AsciiStage } from '../engine/stage';
import type { AsciiScene } from '../engine/types';
export interface AsciiCanvasProps {
/** Builds the scene. Called again only when `sceneKey` changes. */
scene: () => AsciiScene;
/** Changes when the scene should be rebuilt, such as a JSON string of its options. */
sceneKey?: string;
/** Font size of each cell in CSS pixels. Default 14. */
cellSize?: number;
/** Follow the pointer and answer clicks. Default true. */
interactive?: boolean;
/** How fast the scene's clock runs: 0.5 is half speed, 2 is double. Default 1. */
speed?: number;
/**
* Describes the picture for screen readers. Without one the canvas is decorative and hidden
* from assistive technology, which suits a background.
*/
label?: string;
className?: string;
style?: CSSProperties;
}
/**
* A canvas that runs an ASCII scene. It fills its parent; give the parent a size. Set the type
* with CSS `font-family` (a monospace face) and the ink with `color`.
*/
export function AsciiCanvas({
scene,
sceneKey,
cellSize,
interactive,
speed,
label,
className,
style,
}: AsciiCanvasProps) {
const canvasRef = useRef<HTMLCanvasElement>(null);
const stageRef = useRef<AsciiStage | null>(null);
const latest = useRef({ scene, cellSize, interactive, speed });
latest.current = { scene, cellSize, interactive, speed };
// A new scene starts a new world; everything else is tuned on the running stage.
useEffect(() => {
const canvas = canvasRef.current;
if (!canvas) return;
const { scene: build, ...options } = latest.current;
const stage = new AsciiStage(canvas, build(), options);
stageRef.current = stage;
return () => {
stage.destroy();
stageRef.current = null;
};
}, [sceneKey]);
useEffect(() => {
stageRef.current?.configure({ cellSize, interactive, speed });
}, [cellSize, interactive, speed]);
const ink = style?.color;
useEffect(() => {
stageRef.current?.refresh();
}, [ink]);
return (
<canvas
ref={canvasRef}
className={className ? `lilt-ascii ${className}` : 'lilt-ascii'}
style={{ display: 'block', width: '100%', height: '100%', ...style }}
{...(label ? { role: 'img', 'aria-label': label } : { 'aria-hidden': true })}
/>
);
}
export type SceneProps<Options> = Options & Omit<AsciiCanvasProps, 'scene' | 'sceneKey'>;
/** Splits a scene's own options from the canvas props. */
export function useSceneProps<Options extends object>(
props: SceneProps<Options>,
create: (options: Options) => AsciiScene,
): AsciiCanvasProps {
const { cellSize, interactive, speed, label, className, style, ...options } = props;
return {
scene: () => create(options as Options),
sceneKey: JSON.stringify(options),
cellSize,
interactive,
speed,
label,
className,
style,
};
}
components/lilt/ascii/engine/noise.tsascii-engine
noise.ts
/** A stable pseudo-random number in [0, 1) for an integer lattice point. */
export function hash3(x: number, y: number, z: number): number {
let h =
Math.imul(x | 0, 0x27d4eb2d) ^ Math.imul(y | 0, 0x165667b1) ^ Math.imul(z | 0, 0x9e3779b1);
h = Math.imul(h ^ (h >>> 15), 0x85ebca6b);
h = Math.imul(h ^ (h >>> 13), 0xc2b2ae35);
return ((h ^ (h >>> 16)) >>> 0) / 4294967296;
}
const fade = (t: number) => t * t * (3 - 2 * t);
const mix = (a: number, b: number, t: number) => a + (b - a) * t;
/** Smooth value noise in [0, 1). */
export function noise3(x: number, y: number, z: number): number {
const xi = Math.floor(x);
const yi = Math.floor(y);
const zi = Math.floor(z);
const u = fade(x - xi);
const v = fade(y - yi);
const w = fade(z - zi);
const a = mix(hash3(xi, yi, zi), hash3(xi + 1, yi, zi), u);
const b = mix(hash3(xi, yi + 1, zi), hash3(xi + 1, yi + 1, zi), u);
const c = mix(hash3(xi, yi, zi + 1), hash3(xi + 1, yi, zi + 1), u);
const d = mix(hash3(xi, yi + 1, zi + 1), hash3(xi + 1, yi + 1, zi + 1), u);
return mix(mix(a, b, v), mix(c, d, v), w);
}
/** Layered noise in [0, 1): each octave doubles the detail and halves the weight. */
export function fbm3(x: number, y: number, z: number, octaves = 4): number {
let sum = 0;
let weight = 0.5;
let total = 0;
for (let i = 0; i < octaves; i++) {
sum += noise3(x, y, z) * weight;
total += weight;
weight *= 0.5;
x *= 2.03;
y *= 2.03;
z *= 2.03;
}
return sum / total;
}
export const clamp = (value: number, min: number, max: number) =>
value < min ? min : value > max ? max : value;
export const smoothstep = (edge0: number, edge1: number, x: number) => {
const t = clamp((x - edge0) / (edge1 - edge0), 0, 1);
return t * t * (3 - 2 * t);
};
/** Frame-rate independent easing toward a target: `rate` is the share closed per second. */
export const approach = (current: number, target: number, rate: number, dt: number) =>
target + (current - target) * Math.exp(-rate * dt);
components/lilt/ascii/engine/glyphs.tsascii-engine
glyphs.ts
import { clamp } from './noise';
/** The glyph a share of the way along a ramp of glyphs, sparse to dense. */
export function ramp(glyphs: string, value: number): string {
return glyphs[clamp(Math.floor(value * glyphs.length), 0, glyphs.length - 1)]!;
}
/**
* The stroke that best follows a direction on screen. `dx` and `dy` are in square units (cell
* widths), y down. Used for tentacles, grass and anything else drawn as a line of type.
*/
export function stroke(dx: number, dy: number): string {
const angle = Math.atan2(dy, dx);
// Fold to [0, π): a stroke has no direction.
const a = angle < 0 ? angle + Math.PI : angle;
if (a < Math.PI / 8 || a >= (Math.PI * 7) / 8) return '-';
if (a < (Math.PI * 3) / 8) return '\\';
if (a < (Math.PI * 5) / 8) return '|';
return '/';
}
components/lilt/ascii/engine/surface.tsascii-engine
surface.ts
/** Opacity steps per colour. Cells sharing a colour and step are painted with one fill style. */
export const LEVELS = 8;
/** A glyph code for a small solid square: crisper than a full stop at every font size. */
export const DOT = 1;
/**
* One frame of type: a glyph, colour and opacity per cell, and optionally a solid block behind it.
* Scenes write into it; the stage paints it in batches, one fill style per colour and opacity, so a
* full screen costs a few dozen style changes rather than thousands.
*/
export class GlyphSurface {
cols = 0;
rows = 0;
glyph = new Uint16Array(0);
tone = new Uint8Array(0);
level = new Uint8Array(0);
/** The block behind each cell: its colour, and its opacity step, 0 for none. */
blockTone = new Uint8Array(0);
blockLevel = new Uint8Array(0);
private order = new Int32Array(0);
private counts = new Int32Array(0);
private starts = new Int32Array(0);
resize(cols: number, rows: number) {
this.cols = cols;
this.rows = rows;
const size = cols * rows;
this.glyph = new Uint16Array(size);
this.tone = new Uint8Array(size);
this.level = new Uint8Array(size);
this.blockTone = new Uint8Array(size);
this.blockLevel = new Uint8Array(size);
this.order = new Int32Array(size);
}
clear() {
this.glyph.fill(0);
this.blockLevel.fill(0);
}
/**
* Writes a glyph; later writes replace earlier ones, so draw back to front. `glyph` is a
* character, a char code, or `DOT`. Opacity at or below zero leaves the cell untouched.
*/
put(col: number, row: number, glyph: string | number, tone: number, opacity = 1) {
col = Math.floor(col);
row = Math.floor(row);
if (col < 0 || row < 0 || col >= this.cols || row >= this.rows || opacity <= 0) return;
const i = row * this.cols + col;
this.glyph[i] = typeof glyph === 'number' ? glyph : glyph.charCodeAt(0);
this.tone[i] = tone;
this.level[i] = Math.min(LEVELS, Math.ceil(opacity * LEVELS));
}
/**
* Fills a cell with a solid block of colour, painted behind its glyph. Solid shapes read as one
* mass this way, with a glyph cut into each block, the way a mosaic does. Opacity at or below
* zero removes the block.
*/
fill(col: number, row: number, tone: number, opacity = 1) {
col = Math.floor(col);
row = Math.floor(row);
if (col < 0 || row < 0 || col >= this.cols || row >= this.rows) return;
const i = row * this.cols + col;
this.blockTone[i] = tone;
this.blockLevel[i] = opacity <= 0 ? 0 : Math.min(LEVELS, Math.ceil(opacity * LEVELS));
}
/** True when a cell already holds a glyph or a block this frame. */
filled(col: number, row: number) {
col = Math.floor(col);
row = Math.floor(row);
if (col < 0 || row < 0 || col >= this.cols || row >= this.rows) return false;
const i = row * this.cols + col;
return this.glyph[i] !== 0 || this.blockLevel[i] !== 0;
}
/**
* Sorts cells into buckets of one fill style each, by counting: `bucketOf` gives a cell's bucket,
* or -1 to skip it. Leaves the cells in `order` and returns how many fall in each bucket.
*/
private sort(buckets: number, bucketOf: (i: number) => number) {
if (this.counts.length !== buckets) {
this.counts = new Int32Array(buckets);
this.starts = new Int32Array(buckets);
}
const { order, counts, starts } = this;
counts.fill(0);
const n = this.glyph.length;
for (let i = 0; i < n; i++) {
const b = bucketOf(i);
if (b >= 0 && b < buckets) counts[b]++;
}
let sum = 0;
for (let b = 0; b < buckets; b++) {
starts[b] = sum;
sum += counts[b]!;
}
for (let i = 0; i < n; i++) {
const b = bucketOf(i);
if (b >= 0 && b < buckets) order[starts[b]!++] = i;
}
return counts;
}
/**
* Paints the frame. `styles[tone * LEVELS + level - 1]` is the fill style for each bucket.
* With a monospace font, each bucket's glyphs on a row go out as one string with spaces in the
* gaps: a canvas pays per text call far more than per glyph, so this is many times faster.
*/
paint(
ctx: CanvasRenderingContext2D,
styles: readonly string[],
cw: number,
ch: number,
mono = true,
) {
const buckets = styles.length;
const { glyph, tone, level, blockTone, blockLevel, order, cols } = this;
// Blocks first, each inset a pixel so the grid of type still shows between them.
let counts = this.sort(buckets, (i) =>
blockLevel[i] ? blockTone[i]! * LEVELS + blockLevel[i]! - 1 : -1,
);
let k = 0;
for (let b = 0; b < buckets; b++) {
const count = counts[b]!;
if (!count) continue;
ctx.fillStyle = styles[b]!;
for (const end = k + count; k < end; k++) {
const i = order[k]!;
const col = i % cols;
const row = (i - col) / cols;
ctx.fillRect(col * cw + 0.5, row * ch + 0.5, cw - 1, ch - 1);
}
}
counts = this.sort(buckets, (i) => (glyph[i] ? tone[i]! * LEVELS + level[i]! - 1 : -1));
const dot = Math.max(1.5, Math.round(cw * 0.22));
ctx.textAlign = mono ? 'left' : 'center';
k = 0;
for (let b = 0; b < buckets; b++) {
const count = counts[b];
if (!count) continue;
ctx.fillStyle = styles[b]!;
// A run of text on one row: where it starts, and its characters so far.
let runRow = -1;
let runCol = 0;
let lastCol = 0;
let run = '';
for (const end = k + count; k < end; k++) {
const i = order[k]!;
const col = i % cols;
const row = (i - col) / cols;
const code = glyph[i]!;
if (code === DOT) {
ctx.fillRect(col * cw + cw / 2 - dot / 2, row * ch + ch / 2 - dot / 2, dot, dot);
continue;
}
if (!mono) {
ctx.fillText(String.fromCharCode(code), col * cw + cw / 2, row * ch + ch / 2);
continue;
}
if (row !== runRow) {
if (run) ctx.fillText(run, runCol * cw, runRow * ch + ch / 2);
runRow = row;
runCol = col;
run = '';
} else {
run += ' '.repeat(col - lastCol - 1);
}
run += String.fromCharCode(code);
lastCol = col;
}
if (run) ctx.fillText(run, runCol * cw, runRow * ch + ch / 2);
}
}
}
components/lilt/ascii/engine/types.tsascii-engine
types.ts
import type { GlyphSurface } from './surface';
/** The character grid a scene draws into. Positions are in cells; `aspect` is cell height over width. */
export interface AsciiGrid {
cols: number;
rows: number;
aspect: number;
}
export interface AsciiPointer {
/** Column under the pointer, fractional. */
x: number;
/** Row under the pointer, fractional. */
y: number;
/** False when the pointer is outside the canvas or is a finger that lifted. */
active: boolean;
}
/**
* A living picture made of type. The stage owns the canvas, the clock and input; a scene owns its
* world. `step` runs on a fixed 60 Hz clock and `draw` writes the current frame into the surface.
*/
export interface AsciiScene {
/**
* The scene's colours, addressed by index from `draw`. Any CSS colour works; `ink` is the
* canvas's own text colour, so a scene can follow the page's light or dark theme.
*/
readonly palette: readonly string[];
resize(grid: AsciiGrid): void;
step(dt: number, pointer: AsciiPointer): void;
draw(surface: GlyphSurface): void;
/** A click or tap at a cell. */
press?(x: number, y: number): void;
/**
* Height of a row as a multiple of the font size. Default 1.25. Scenes made of solid shapes ask
* for tighter rows, closer to square cells, so a body lying sideways still spans several rows.
*/
readonly lineHeight?: number;
/** Seconds to run before showing a single still frame when the reader prefers reduced motion. */
readonly settle?: number;
}
Usage
How it behaves.
The scene fills its parent, so give the parent a size. The canvas takes its type from CSS font-family and its ink from color. It pauses off screen and in hidden tabs, and shows one still frame when the reader prefers reduced motion.
Props7
Every option.
Pass these directly to AsciiFireworks.
| Prop | Type | Default | What it does |
|---|---|---|---|
colors | string[] | ['#8b6cff', '#e5489c', '#f5a93c', '#4fb6f0'] | Colours the shells burst in, taken in turn. |
rate | number | 0.55 | Shells launched a second, on average. 0 leaves the sky to your clicks. |
skyline | boolean | true | A low city skyline along the bottom, with lit windows. |
cellSize | number | 14 | Font size of each cell in pixels. Smaller cells draw a finer picture. |
speed | number | 1 | How fast the clock runs: 0.5 is half speed, 2 is double. |
interactive | boolean | true | Follow the pointer and answer clicks. |
label | string | — | Describes the picture for screen readers. Without one it is a hidden background. |