Your pointer is a current that pushes them aside. Click to startle them.
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 { AsciiJellyfish } from '@/components/lilt/ascii/scenes/ascii-jellyfish';
export function Hero() {
return (
<section style={{ height: 560 }}>
<AsciiJellyfish />
</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/jellyfish.jsoncomponents/lilt/ascii/scenes/ascii-jellyfish.tsx
ascii-jellyfish.tsx
'use client';
import { AsciiCanvas, useSceneProps, type SceneProps } from '../react/ascii-canvas';
import { createJellyfish, type JellyfishOptions } from './jellyfish';
/** Jellyfish that pulse to swim and trail swaying tentacles, in drifting marine snow. */
export function AsciiJellyfish(props: SceneProps<JellyfishOptions>) {
return <AsciiCanvas {...useSceneProps(props, createJellyfish)} />;
}
components/lilt/ascii/scenes/jellyfish.ts
jellyfish.ts
import { ramp, stroke } from '../engine/glyphs';
import { approach, clamp, hash3, noise3 } from '../engine/noise';
import { DOT, type GlyphSurface } from '../engine/surface';
import type { AsciiGrid, AsciiPointer, AsciiScene } from '../engine/types';
export interface JellyfishOptions {
/** How many jellyfish. Default 4. */
count?: number;
/** Glow colours, one per jellyfish in turn. Default cyan, violet, pink and amber. */
colors?: readonly string[];
/** Drifting flecks of marine snow per thousand cells. Default 12. */
snow?: number;
}
const INK = 0;
const TENTACLES = 9;
const LINKS = 16;
const ARMS = 4;
const ARM_LINKS = 10;
const RIM = ':-=+*#';
const EDGE = '.:';
interface Rope {
x: Float32Array;
y: Float32Array;
px: Float32Array;
py: Float32Array;
rest: number;
}
interface Jelly {
x: number;
y: number;
vx: number;
vy: number;
/** Lean of the bell from upright, radians; it swims the way it points. */
tilt: number;
radius: number;
/** Through one beat, 0 → 1. */
beat: number;
period: number;
tone: number;
/** A startled flash, easing away. */
flash: number;
/** 0.6 far and dim → 1 near. */
depth: number;
tentacles: Rope[];
arms: Rope[];
seed: number;
}
/** How hard the bell is squeezing at a point in its beat: a quick squeeze, then a long glide. */
const squeeze = (beat: number) => (beat < 0.3 ? Math.sin((beat / 0.3) * Math.PI) : 0);
/** How much of a cell a shape covers, from its signed distance in square units. */
const coverage = (d: number) => clamp(0.5 - d / 1.3, 0, 1);
function rope(links: number, rest: number, x: number, y: number): Rope {
const r: Rope = {
x: new Float32Array(links),
y: new Float32Array(links),
px: new Float32Array(links),
py: new Float32Array(links),
rest,
};
for (let i = 0; i < links; i++) {
r.x[i] = r.px[i] = x;
r.y[i] = r.py[i] = y + i * rest;
}
return r;
}
/**
* Jellyfish in deep water. Each bell is a glassy dome, lit at its rim, with radial canals and
* four soft gonads showing through; it squeezes to jet upward and relaxes to glide. Frilled oral
* arms and long fine tentacles trail as ropes that sway and lag behind it. Marine snow drifts
* past. The pointer is a current that pushes everything gently aside; a click startles nearby
* jellyfish into a flash and a quick escape.
*/
export function createJellyfish(options: JellyfishOptions = {}): AsciiScene {
const count = clamp(Math.round(options.count ?? 4), 1, 16);
const colours = options.colors?.length
? options.colors
: ['#5ee7ff', '#a78bfa', '#ff7ad9', '#ffc36b'];
const snowDensity = options.snow ?? 12;
let grid: AsciiGrid = { cols: 0, rows: 0, aspect: 2 };
let width = 0;
let height = 0;
const jellies: Jelly[] = [];
let snow: { x: number; y: number; seed: number }[] = [];
let time = 0;
let current = { x: 0, y: 0, active: false, vx: 0, vy: 0 };
function populate() {
jellies.length = 0;
const base = Math.min(width, height);
for (let k = 0; k < count; k++) {
const depth = 0.6 + 0.4 * hash3(k, 2, 5);
const radius = base * (0.075 + 0.055 * depth);
const x = width * (0.1 + 0.8 * ((k + 0.5) / count) + (hash3(k, 3, 5) - 0.5) * 0.1);
const y = height * (0.3 + 0.35 * hash3(k, 4, 5));
const tentacles: Rope[] = [];
for (let t = 0; t < TENTACLES; t++) {
// Each a little different in length, so the ends don't line up.
const rest = radius * (0.2 + 0.08 * hash3(k, t, 11));
tentacles.push(rope(LINKS, rest, x, y));
}
const arms: Rope[] = [];
for (let t = 0; t < ARMS; t++) arms.push(rope(ARM_LINKS, radius * 0.2, x, y));
jellies.push({
x,
y,
vx: 0,
vy: 0,
tilt: (hash3(k, 6, 5) - 0.5) * 0.6,
radius,
beat: hash3(k, 7, 5),
period: 2.4 + hash3(k, 8, 5) * 1.4,
tone: 1 + (k % colours.length),
flash: 0,
depth,
tentacles,
arms,
seed: k * 13.7,
});
}
// Far jellies first, so near ones pass in front.
jellies.sort((a, b) => a.depth - b.depth);
const n = Math.round(((grid.cols * grid.rows) / 1000) * snowDensity);
snow = Array.from({ length: n }, (_, i) => ({
x: Math.random() * width,
y: Math.random() * height,
seed: i,
}));
}
/** A point just inside the bell's margin, a share of the way across it (-1 → 1). */
function margin(j: Jelly, across: number) {
const half = j.radius * (1 - 0.18 * squeeze(j.beat));
const ux = Math.cos(j.tilt);
const uy = Math.sin(j.tilt);
return { x: j.x + ux * half * across * 0.92, y: j.y + uy * half * across * 0.92 };
}
function stepRope(r: Rope, ax: number, ay: number, dt: number, sway: number) {
r.x[0] = ax;
r.y[0] = ay;
r.px[0] = ax;
r.py[0] = ay;
const drag = Math.exp(-2.4 * dt);
const n = r.x.length;
for (let i = 1; i < n; i++) {
const vx = (r.x[i]! - r.px[i]!) * drag;
const vy = (r.y[i]! - r.py[i]!) * drag;
r.px[i] = r.x[i]!;
r.py[i] = r.y[i]!;
// Water sways the strands more toward their ends; a little weight hangs them.
// A slow wave travels down each strand, so it ripples rather than hangs.
const flow =
(noise3(i * 0.25 + sway, time * 0.5, sway) - 0.5) * (2 + (i / n) * 4) +
Math.sin(i * 0.5 - time * 1.4 + sway) * (i / n) * 2.5;
let fx = flow;
let fy = 3.5;
if (current.active) {
const dx = r.x[i]! - current.x;
const dy = r.y[i]! - current.y;
const d2 = dx * dx + dy * dy;
const reach = 14 * 14;
if (d2 < reach) {
const k = 1 - d2 / reach;
fx += current.vx * k * 0.6 + (dx / Math.sqrt(d2 + 1)) * k * 10;
fy += current.vy * k * 0.6 + (dy / Math.sqrt(d2 + 1)) * k * 10;
}
}
// However hard the bell jerks, a strand only moves so far in a step.
const cap = r.rest * 0.5;
r.x[i] = r.x[i]! + clamp(vx, -cap, cap) + fx * dt * dt;
r.y[i] = r.y[i]! + clamp(vy, -cap, cap) + fy * dt * dt;
}
// Pull each link back to its length, from the bell down, a few times over.
for (let pass = 0; pass < 3; pass++) {
for (let i = 1; i < n; i++) {
const dx = r.x[i]! - r.x[i - 1]!;
const dy = r.y[i]! - r.y[i - 1]!;
const d = Math.hypot(dx, dy) || 1;
const k = r.rest / d;
r.x[i] = r.x[i - 1]! + dx * k;
r.y[i] = r.y[i - 1]! + dy * k;
}
}
}
function swim(j: Jelly, dt: number) {
const before = j.beat;
j.beat = (j.beat + dt / j.period) % 1;
const s = squeeze(j.beat);
// The bell points up its own axis: (sin tilt, -cos tilt).
const ax = Math.sin(j.tilt);
const ay = -Math.cos(j.tilt);
const thrust = s * 20 * (0.7 + j.depth * 0.5);
j.vx += ax * thrust * dt;
j.vy += ay * thrust * dt;
// Between beats it sinks slowly.
j.vy += 1.2 * dt;
if (current.active) {
const dx = j.x - current.x;
const dy = j.y - current.y;
const d = Math.hypot(dx, dy);
if (d < 18 && d > 0.01) {
j.vx += (dx / d) * (1 - d / 18) * 14 * dt + current.vx * 0.04 * dt;
j.vy += (dy / d) * (1 - d / 18) * 14 * dt + current.vy * 0.04 * dt;
}
}
// Jellies drift apart rather than through each other.
for (const other of jellies) {
if (other === j) continue;
const dx = j.x - other.x;
const dy = j.y - other.y;
const d = Math.hypot(dx, dy);
const room = (j.radius + other.radius) * 1.6;
if (d < room && d > 0.01) {
j.vx += (dx / d) * (1 - d / room) * 6 * dt;
j.vy += (dy / d) * (1 - d / room) * 3 * dt;
}
}
const drag = Math.exp(-1.3 * dt);
j.vx *= drag;
j.vy *= drag;
j.x += j.vx * dt;
j.y += j.vy * dt;
// Steer by leaning: toward the middle when near a side, and over the top when it gets there.
let lean = (noise3(j.seed, time * 0.08, 2) - 0.5) * 0.9;
const m = j.radius * 2.5;
if (j.x < m) lean += 0.6;
if (j.x > width - m) lean -= 0.6;
if (j.y < height * 0.18) lean += Math.sign(width / 2 - j.x || 1) * 0.5;
j.tilt = approach(j.tilt, clamp(lean, -1.3, 1.3), 0.5, dt);
// In the upper water it rests between beats and lets itself sink back down.
if (j.y < height * 0.3 + j.radius && j.beat < before) j.beat = 0.35;
if (j.y > height - j.radius) {
j.y = height - j.radius;
j.vy = Math.min(j.vy, 0);
}
j.flash = approach(j.flash, 0, 1.6, dt);
for (let t = 0; t < TENTACLES; t++) {
const at = margin(j, -1 + (2 * t) / (TENTACLES - 1));
stepRope(j.tentacles[t]!, at.x, at.y, dt, j.seed + t);
}
for (let t = 0; t < ARMS; t++) {
const at = margin(j, -0.4 + (0.8 * t) / (ARMS - 1));
stepRope(j.arms[t]!, at.x, at.y, dt, j.seed + 20 + t);
}
}
/** Brightness of a jelly: far ones are dimmer, and a fright lights it up. */
const glowOf = (j: Jelly) => Math.min(1, 0.5 + j.depth * 0.5 + j.flash * 0.5);
/** A tentacle: one fine strand of type, fading toward its end. */
function drawTentacle(surface: GlyphSurface, r: Rope, j: Jelly) {
const { aspect } = grid;
const n = r.x.length;
const glow = glowOf(j);
for (let i = 1; i < n; i++) {
const ax = r.x[i - 1]!;
const ay = r.y[i - 1]!;
const bx = r.x[i]!;
const by = r.y[i]!;
const fade = 1 - i / n;
const g = stroke(bx - ax, by - ay);
// Walk the link in steps smaller than a cell so the strand never breaks.
const steps = Math.max(1, Math.ceil(Math.hypot(bx - ax, (by - ay) / aspect) * 1.5));
for (let k = 0; k < steps; k++) {
const t = k / steps;
const x = ax + (bx - ax) * t;
const y = (ay + (by - ay) * t) / aspect;
surface.put(x, y, g, j.tone, (0.08 + 0.6 * fade) * glow);
}
}
}
/** An oral arm: a frilled ribbon, widest near the bell, its edges rippling. */
function drawArm(surface: GlyphSurface, r: Rope, j: Jelly, which: number) {
const { aspect } = grid;
const n = r.x.length;
const glow = glowOf(j);
for (let i = 1; i < n; i++) {
const ax = r.x[i - 1]!;
const ay = r.y[i - 1]!;
const tx = r.x[i]! - ax;
const ty = r.y[i]! - ay;
const tl = Math.hypot(tx, ty) || 1;
const steps = Math.max(1, Math.ceil(tl * 1.2));
for (let k = 0; k < steps; k++) {
const t = k / steps;
const along = (i - 1 + t) / (n - 1);
const frill = 0.75 + 0.45 * Math.sin(along * 14 - time * 2.2 + which * 1.7);
const half = j.radius * 0.08 * (1 - along * 0.5) * frill + 0.3;
const fade = 1 - along * 0.85;
const cx = ax + tx * t;
const cy = ay + ty * t;
for (let o = -half; o <= half; o += 0.7) {
const x = cx - (ty / tl) * o;
const y = (cy + (tx / tl) * o) / aspect;
const edge = Math.abs(o) / half;
if (edge < 0.6) {
surface.fill(x, y, j.tone, (0.06 + 0.14 * fade) * glow);
surface.put(x, y, stroke(tx, ty), j.tone, (0.3 + 0.45 * fade) * glow);
} else {
surface.put(x, y, ramp(EDGE, 1 - edge), j.tone, (0.3 + 0.4 * fade) * glow);
}
}
}
}
}
function drawBell(surface: GlyphSurface, j: Jelly) {
const { aspect, cols, rows } = grid;
const s = squeeze(j.beat);
const half = j.radius * (1 - 0.18 * s);
const tall = j.radius * (1 + 0.3 * s);
const glow = glowOf(j);
const cos = Math.cos(j.tilt);
const sin = Math.sin(j.tilt);
const reach = Math.max(half, tall) * 1.5;
const c0 = Math.max(0, Math.floor(j.x - reach));
const c1 = Math.min(cols - 1, Math.ceil(j.x + reach));
const r0 = Math.max(0, Math.floor((j.y - reach) / aspect));
const r1 = Math.min(rows - 1, Math.ceil((j.y + reach) / aspect));
const size = Math.min(half, tall);
for (let row = r0; row <= r1; row++) {
for (let col = c0; col <= c1; col++) {
const dx = col + 0.5 - j.x;
const dy = (row + 0.5) * aspect - j.y;
// Into the bell's frame: u across, w up from the margin, both scaled to the bell.
const u = (dx * cos + dy * sin) / half;
const w = (dx * sin - dy * cos) / tall;
if (w < -0.2) continue;
const e = Math.hypot(u, Math.max(0, w));
const dome = coverage((e - 1) * size);
if (dome <= 0.05) {
// A soft halo of light in the water around it.
const halo = 1 - (e - 1) / 0.35;
if (halo > 0 && w > 0 && hash3(col, row, 3) < halo * 0.35)
surface.put(col, row, DOT, j.tone, halo * 0.3 * glow);
continue;
}
// The underside arcs up into the bell: through it, the inside of the dome shows faintly.
const mouth = 0.2 * (1 - u * u);
const c = Math.min(dome, coverage((mouth - w) * tall));
if (c <= 0.05) continue;
if (c < 0.55) {
surface.put(col, row, ramp(EDGE, c * 2), j.tone, 0.75 * glow);
continue;
}
// Glassy: the rim glows where the dome turns away from you, and the middle is clear.
const rim = Math.pow(clamp(e, 0, 1), 5);
const angle = Math.atan2(u, w + 0.25);
const canal = Math.abs(Math.sin(angle * 8)) < 0.2 && e > 0.3 && e < 0.92;
// Four soft gonads in a ring around the middle.
const ring = 1 - Math.abs(e - 0.45) / 0.14;
const gonad = ring > 0 && Math.cos(Math.atan2(w - 0.1, u) * 4 + 0.6) > 0.3 ? ring : 0;
const sheen = Math.max(0, 1 - Math.hypot(u + 0.35, w - 0.62) / 0.3);
const v = 0.1 + 0.55 * rim + 0.25 * gonad + 0.35 * sheen;
surface.fill(col, row, j.tone, clamp(v, 0, 1) * glow);
if (rim > 0.35) surface.put(col, row, ramp(RIM, rim), INK, (0.25 + 0.5 * rim) * glow);
else if (sheen > 0.3) surface.put(col, row, '.', INK, 0.6 * glow);
else if (canal) surface.put(col, row, stroke(u, -w), j.tone, 0.6 * glow);
}
}
}
return {
palette: ['ink', ...colours],
lineHeight: 0.9,
settle: 4,
resize(next) {
grid = next;
width = grid.cols;
height = grid.rows * grid.aspect;
populate();
// Let the ropes fall into place before anyone sees them.
for (let i = 0; i < 90; i++) for (const j of jellies) swim(j, 1 / 60);
},
step(dt, pointer: AsciiPointer) {
if (!jellies.length) return;
time += dt;
const x = pointer.x;
const y = pointer.y * grid.aspect;
current = {
x,
y,
active: pointer.active,
vx:
current.active && pointer.active ? approach(current.vx, (x - current.x) / dt, 8, dt) : 0,
vy:
current.active && pointer.active ? approach(current.vy, (y - current.y) / dt, 8, dt) : 0,
};
for (const j of jellies) swim(j, dt);
for (const f of snow) {
f.y += (0.8 + hash3(f.seed, 0, 1) * 1.2) * dt;
f.x += (noise3(f.seed, time * 0.2, 4) - 0.5) * 2 * dt;
if (current.active) {
const dx = f.x - current.x;
const dy = f.y - current.y;
const d2 = dx * dx + dy * dy;
if (d2 < 100) {
f.x += (dx / Math.sqrt(d2 + 1)) * (1 - d2 / 100) * 8 * dt;
f.y += (dy / Math.sqrt(d2 + 1)) * (1 - d2 / 100) * 8 * dt;
}
}
if (f.y > height) {
f.y = 0;
f.x = Math.random() * width;
}
}
},
press(px, py) {
const x = px;
const y = py * grid.aspect;
for (const j of jellies) {
const d = Math.hypot(j.x - x, j.y - y);
if (d > Math.min(width, height) * 0.5) continue;
j.flash = 1;
// Turn away and squeeze at once.
j.tilt = clamp(Math.atan2(j.x - x, -(j.y - y)), -1.3, 1.3);
j.beat = 0;
}
},
draw(surface: GlyphSurface) {
const { aspect } = grid;
// Back to front: tentacles, then arms, then the bell over them, one jelly at a time.
for (const j of jellies) {
for (const t of j.tentacles) drawTentacle(surface, t, j);
j.arms.forEach((arm, k) => drawArm(surface, arm, j, k));
drawBell(surface, j);
}
for (const f of snow) {
if (surface.filled(f.x, f.y / aspect)) continue;
const twinkle = 0.5 + 0.5 * Math.sin(time * 1.3 + f.seed);
surface.put(f.x, f.y / aspect, DOT, INK, 0.12 + 0.2 * twinkle);
}
},
};
}
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 AsciiJellyfish.
| Prop | Type | Default | What it does |
|---|---|---|---|
colors | string[] | ['#5ee7ff', '#a78bfa', '#ff7ad9', '#ffc36b'] | Glow colours, one per jellyfish in turn. |
count | number | 4 | How many jellyfish. |
snow | number | 12 | Drifting flecks of marine snow per thousand cells. |
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. |