Skip to content
Charts55Components12Visuals14ASCII45
GitHubGet startedGet started
All ASCIISnowNature
PreviousNext: Bonsai

Your pointer is a warm breath that melts the caps and blows flakes aside. Click to shake the snow off.

Snow

Nature

Snow falling on a word. It caps the letters, drifts on the ground, and slowly melts.

Customize 8

Letters
#d6e0f2
1.00
1.5
14px
1.00
Install & copy sourceInstall & copy sourceSee propsSee props10

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 { AsciiSnow } from '@/components/lilt/ascii/more-scenes/ascii-snow';

export function Hero() {
  return (
    <section style={{ height: 560 }}>
      <AsciiSnow />
    </section>
  );
}

Installation9

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/snow.json
components/lilt/ascii/more-scenes/ascii-snow.tsx

ascii-snow.tsx

'use client';

import { AsciiCanvas, useSceneProps, type SceneProps } from '../react/ascii-canvas';
import { createSnow, type SnowOptions } from './snow';

/** Snow falling on a word: it caps the letters, drifts on the ground, and melts at the pointer. */
export function AsciiSnow(props: SceneProps<SnowOptions>) {
  return <AsciiCanvas {...useSceneProps(props, createSnow)} />;
}
components/lilt/ascii/more-scenes/snow.ts

snow.ts

import { ramp } from '../engine/glyphs';
import { approach, clamp, hash3, noise3, smoothstep } from '../engine/noise';
import { DOT, type GlyphSurface } from '../engine/surface';
import type { AsciiGrid, AsciiPointer, AsciiScene } from '../engine/types';
import { gradient, rasteriseWord } from './shared';

export interface SnowOptions {
  /** A word standing in the snow, which catches it on its letters. Empty for none. Default 'winter'. */
  text?: string;
  /** Colours of the letters, left to right. Default violet to rose. */
  colors?: readonly string[];
  /** Colour of the snow. Default a cool white that also shows on a light page. */
  snow?: string;
  /** How hard it snows, 0 to 2. Default 1. */
  density?: number;
  /** The steady wind, in columns a second; gusts come and go around it. Default 1.5. */
  wind?: number;
  /**
   * A precomputed coverage mask for the word, one value a cell, for hosts without a canvas to
   * draw text on. Normally the word is drawn for you.
   */
  mask?: (cols: number, rows: number, aspect: number) => Float32Array | null;
}

const SNOW = 0;
/** The dark cut into solid blocks. */
const DEEP = 1;
/** The letters' colours start here. */
const LETTER = 2;
const STEPS = 8;
/** The deepest a cap on a letter grows, in rows. */
const CAP = 2.6;

/** Glyphs cut into the letters: sparse where the light catches them, dense in shadow. */
const CUT = '.:-=';
const EDGE = '.:';

/** Light from the upper left and in front: x, y (down), z (toward the viewer). */
const LIGHT = [-0.5, -0.6, 0.62].map((v, _, a) => v / Math.hypot(...a));

interface Flake {
  x: number;
  y: number;
  /** 0 far → 1 near: near flakes are bigger, brighter, faster, and land on things. */
  depth: number;
  vx: number;
  vy: number;
  phase: number;
}

interface Clump {
  x: number;
  y: number;
  vx: number;
  vy: number;
  /** Snow it carries, in rows of depth; puffs of powder carry none. */
  amount: number;
  age: number;
  life: number;
}

/**
 * Snow falling on a word. Flakes fall in three depths, the near ones larger and brighter, and
 * drift on gusts of wind. The snow piles up: it caps the tops of the letters, sliding off their
 * edges once a cap grows steep, and drifts against them on the ground. The piles settle and slowly
 * melt, so they never bury the scene. The pointer is a warm breath that melts the caps and blows
 * the flakes aside; a click shakes the snow off the letters.
 */
export function createSnow(options: SnowOptions = {}): AsciiScene {
  const text = options.text ?? 'winter';
  const stops = options.colors?.length ? options.colors : ['#8b6cff', '#e5489c'];
  const density = clamp(options.density ?? 1, 0, 2);
  const baseWind = options.wind ?? 1.5;
  let grid: AsciiGrid = { cols: 0, rows: 0, aspect: 2 };
  /** Letter coverage per cell, and whether a cell is solid. */
  let mask = new Float32Array(0);
  let solid = new Uint8Array(0);
  /** A softened copy of the mask, whose slope lights the letters as if bevelled. */
  let soft = new Float32Array(0);
  /** Snow lying on each top face, in rows, keyed by the cell of the face. The ground is row `rows`. */
  let depth = new Float32Array(0);
  /** The row below the solid run above each face: how deep the snow there can get. */
  let ceiling = new Int16Array(0);
  /** The first face the sky sees in each column. */
  let open = new Int16Array(0);
  /** Every top face, as a cell index in the extended grid (rows + 1 rows). */
  let faces = new Int32Array(0);
  /** Each cell's colour along the letters' gradient. */
  let hue = new Uint8Array(0);
  const flakes: Flake[] = [];
  const clumps: Clump[] = [];
  let time = 0;
  let wind = baseWind;
  let tick = 0;
  let px = 0;
  let py = 0;
  let breath = 0;

  const cap = () => Math.max(3, grid.rows * 0.15);
  const isSolid = (col: number, row: number) =>
    row >= grid.rows ||
    (row >= 0 && col >= 0 && col < grid.cols && solid[row * grid.cols + col] === 1);

  /** The face snow at a cell would rest on: the first solid below it (or the cell's own run). */
  function faceBelow(col: number, row: number) {
    let r = Math.max(0, Math.floor(row));
    if (isSolid(col, r)) {
      while (r > 0 && isSolid(col, r - 1)) r--;
      return r;
    }
    while (!isSolid(col, r)) r++;
    return r;
  }

  const key = (col: number, row: number) => row * grid.cols + col;

  function build() {
    const { cols, rows, aspect } = grid;
    const size = cols * rows;
    mask = new Float32Array(size);
    solid = new Uint8Array(size);
    soft = new Float32Array(size);
    hue = new Uint8Array(size);
    depth = new Float32Array(cols * (rows + 1));
    ceiling = new Int16Array(cols * (rows + 1));
    open = new Int16Array(cols);

    // The word stands on the ground, filling most of the width and under half the height.
    const word =
      options.mask?.(cols, rows, aspect) ??
      rasteriseWord(
        text,
        cols,
        rows,
        aspect,
        {
          x: cols * 0.1,
          y: rows * 0.42 * aspect,
          width: cols * 0.8,
          height: (rows * 0.58 - 1.5) * aspect,
        },
        800,
        'bottom',
      );
    if (word && word.length === size) mask.set(word);
    for (let i = 0; i < size; i++) solid[i] = mask[i]! >= 0.5 ? 1 : 0;

    // Soften the mask twice with a small box, for the bevel.
    const tmp = new Float32Array(size);
    soft.set(mask);
    for (let pass = 0; pass < 2; pass++) {
      for (let row = 0; row < rows; row++) {
        for (let col = 0; col < cols; col++) {
          let sum = 0;
          let n = 0;
          for (let dy = -1; dy <= 1; dy++) {
            for (let dx = -1; dx <= 1; dx++) {
              const c = col + dx;
              const r = row + dy;
              if (c < 0 || r < 0 || c >= cols || r >= rows) continue;
              sum += soft[r * cols + c]!;
              n++;
            }
          }
          tmp[row * cols + col] = sum / n;
        }
      }
      soft.set(tmp);
    }

    let left = cols;
    let right = 0;
    for (let i = 0; i < size; i++) {
      if (!solid[i]) continue;
      left = Math.min(left, i % cols);
      right = Math.max(right, i % cols);
    }
    for (let i = 0; i < size; i++) {
      const t = right > left ? clamp(((i % cols) - left) / (right - left), 0, 1) : 0;
      hue[i] = Math.round(t * (STEPS - 1));
    }

    // Top faces: a solid cell (or the ground) with air above it.
    const list: number[] = [];
    for (let col = 0; col < cols; col++) {
      for (let row = 0; row <= rows; row++) {
        if (!isSolid(col, row) || isSolid(col, row - 1) || row === 0) continue;
        let r = row - 1;
        while (r > 0 && !isSolid(col, r - 1)) r--;
        list.push(key(col, row));
        ceiling[key(col, row)] = row - r;
      }
      open[col] = faceBelow(col, 0);
    }
    faces = Int32Array.from(list);

    // Begin with a drift on the ground and a dusting on the letters.
    for (const f of faces) {
      const col = f % cols;
      const row = Math.floor(f / cols);
      if (row === rows) depth[f] = 1.2 + 1.6 * noise3(col * 0.06, 3, 1);
      else if (open[col] === row) depth[f] = 0.6;
    }
  }

  function makeFlake(fresh: boolean): Flake {
    const r = Math.random();
    const d = r < 0.55 ? 0.1 + Math.random() * 0.2 : r < 0.85 ? 0.5 : 0.9 + Math.random() * 0.1;
    const upwind = wind > 0 ? -grid.rows * 0.4 : 0;
    return {
      x: upwind + Math.random() * (grid.cols + grid.rows * 0.4),
      y: fresh ? Math.random() * grid.rows : -1 - Math.random() * 3,
      depth: d,
      vx: 0,
      vy: 0,
      phase: Math.random() * Math.PI * 2,
    };
  }

  /** Lays snow on a face, up to what fits under whatever is above it. */
  function deposit(face: number, amount: number) {
    // Whatever would pile past the limit melts away as it lands.
    depth[face] = clamp(depth[face]! + amount, 0, limitOf(face));
  }

  /** The most snow a face holds: a cap on a letter, a drift on the ground, or what fits below. */
  function limitOf(face: number) {
    if (face < grid.rows * grid.cols) return Math.min(ceiling[face]! - 0.2, CAP);
    // Drifts on the ground rise and fall along it, like dunes.
    const col = face % grid.cols;
    return Math.min(ceiling[face]! - 0.2, cap() * (0.45 + 0.8 * noise3(col * 0.045, 5, 2)));
  }

  /** The highest snow-covered row in a column at a face. */
  const topOf = (face: number) => Math.floor(face / grid.cols) - depth[face]!;

  function land(col: number, row: number, amount: number) {
    if (col < 0 || col >= grid.cols) return;
    const face = faceBelow(col, row);
    // A flake that hits the side of a letter far below its top sticks there and is lost.
    if (isSolid(col, Math.floor(row)) && Math.floor(row) - face > 1) return;
    deposit(key(col, face), amount);
  }

  /** Snow slumps toward lower neighbours, and slides off the edges of the letters as clumps. */
  function settle() {
    const { cols } = grid;
    for (const f of faces) {
      const d = depth[f]!;
      if (d < 0.3) continue;
      const col = f % cols;
      const row = Math.floor(f / cols);
      const top = row - d;
      for (const dir of [-1, 1]) {
        const c = col + dir;
        if (c < 0 || c >= cols) continue;
        const startRow = Math.floor(top + 0.5);
        if (isSolid(c, startRow)) continue;
        const nr = faceBelow(c, startRow);
        const nf = key(c, nr);
        const diff = topOf(nf) - top;
        if (nr - row > 1) {
          // An edge: the snow holds a little, then slides off and falls.
          if (d > 1.2 && diff > 1) {
            const chunk = d - 0.5;
            depth[f] = d - chunk;
            clumps.push({
              x: c + 0.5,
              y: top,
              vx: dir * (1 + Math.random() * 2),
              vy: 0,
              amount: chunk,
              age: 0,
              life: 6,
            });
          }
          continue;
        }
        if (diff > 0.75) {
          const move = Math.min(depth[f]!, (diff - 0.75) * 0.25);
          depth[f] = depth[f]! - move;
          deposit(nf, move);
        }
      }
      // Slow melt, and faster where a pile has grown past what it can hold.
      const over = smoothstep(0.6, 1, depth[f]! / limitOf(f));
      depth[f] = Math.max(0, depth[f]! - (0.004 + over * 0.1) / 20);
    }
  }

  function shake() {
    const { cols, rows } = grid;
    for (const f of faces) {
      const row = Math.floor(f / cols);
      const d = depth[f]!;
      if (row === rows || d < 0.2) continue;
      const col = f % cols;
      const lose = d * 0.85;
      depth[f] = d - lose;
      clumps.push({
        x: col + 0.5,
        y: row - d,
        vx: (Math.random() - 0.5) * 6,
        vy: -2 - Math.random() * 4,
        amount: lose,
        age: 0,
        life: 6,
      });
      if (Math.random() < 0.5) puff(col + 0.5, row - d, 2);
    }
  }

  function puff(x: number, y: number, n: number, awayX = 0, awayY = 0) {
    for (let k = 0; k < n; k++) {
      const a = Math.random() * Math.PI * 2;
      const s = 2 + Math.random() * 5;
      clumps.push({
        x,
        y,
        vx: Math.cos(a) * s + awayX,
        vy: (Math.sin(a) * s) / grid.aspect - 1 + awayY,
        amount: 0,
        age: 0,
        life: 0.8 + Math.random() * 0.8,
      });
    }
  }

  return {
    palette: [options.snow ?? '#d6e0f2', '#0b0c12', ...gradient(stops, STEPS)],
    lineHeight: 1,
    settle: 4,
    resize(next) {
      // Measuring the font again can resize to the same grid: keep the snow that has fallen.
      const same =
        next.cols === grid.cols && next.rows === grid.rows && next.aspect === grid.aspect;
      grid = next;
      if (same) return;
      flakes.length = 0;
      clumps.length = 0;
      build();
      const n = Math.round(((grid.cols * grid.rows) / 1000) * 22 * density);
      for (let i = 0; i < n; i++) flakes.push(makeFlake(true));
    },
    step(dt, pointer: AsciiPointer) {
      if (!grid.cols) return;
      const { cols, rows, aspect } = grid;
      time += dt;
      // Gusts: the wind swells and drops on a slow noise.
      const gust = noise3(time * 0.12, 0, 7);
      wind = baseWind * (0.4 + 1.4 * gust) + (noise3(time * 0.05, 4, 1) - 0.5) * 3;
      breath = approach(breath, pointer.active ? 1 : 0, 4, dt);
      if (pointer.active) {
        px = pointer.x;
        py = pointer.y;
      }

      for (const f of flakes) {
        const fall = 2.2 + f.depth * 5.5;
        const sway = Math.sin(time * (0.8 + f.depth) + f.phase) * (0.6 + f.depth);
        let pushX = 0;
        let pushY = 0;
        if (breath > 0.05) {
          // The breath pushes flakes away from the pointer, near ones the most.
          const dx = f.x - px;
          const dy = (f.y - py) * aspect;
          const d = Math.hypot(dx, dy);
          if (d < 12 && d > 0.01) {
            const k = (1 - d / 12) * breath * 40 * (0.3 + f.depth);
            pushX = (dx / d) * k;
            pushY = ((dy / d) * k) / aspect;
          }
        }
        f.vx = approach(f.vx, wind * (0.4 + f.depth * 0.8) + sway + pushX, 3, dt);
        f.vy = approach(f.vy, fall + pushY, 3, dt);
        f.x += f.vx * dt;
        f.y += f.vy * dt;
        const col = Math.floor(f.x);
        const row = Math.floor(f.y);
        if (f.y > rows + 1 || f.x < -grid.rows || f.x > cols + grid.rows) {
          Object.assign(f, makeFlake(false));
          continue;
        }
        if (col < 0 || col >= cols || row < 0) continue;
        if (f.depth < 0.4) {
          // Far flakes fall behind the word and melt into the drift.
          const top = topOf(key(col, rows));
          if (f.y > top) Object.assign(f, makeFlake(false));
          continue;
        }
        // Near flakes land on letters, caps and the drift.
        const face = faceBelow(col, row);
        if (f.y >= topOf(key(col, face))) {
          land(col, row, 0.035 + f.depth * 0.03);
          Object.assign(f, makeFlake(false));
        }
      }

      for (let i = clumps.length - 1; i >= 0; i--) {
        const c = clumps[i]!;
        c.age += dt;
        if (c.amount > 0) {
          c.vy += 30 * dt;
          c.vx = approach(c.vx, wind * 0.3, 1, dt);
        } else {
          c.vx = approach(c.vx, wind, 2, dt);
          c.vy = approach(c.vy, 1.5, 2, dt);
        }
        c.x += c.vx * dt;
        c.y += c.vy * dt;
        const col = Math.floor(c.x);
        const row = Math.floor(c.y);
        if (c.age > c.life || col < 0 || col >= cols || c.y > rows + 1) {
          clumps.splice(i, 1);
          continue;
        }
        if (c.amount > 0 && row >= 0) {
          const face = faceBelow(col, row);
          if (c.y >= topOf(key(col, face))) {
            land(col, row, c.amount);
            if (c.amount > 0.2) puff(c.x, c.y, 2);
            clumps.splice(i, 1);
          }
        }
      }

      // The piles settle at 20 Hz: snow falls on every face open to the sky, unevenly, and slumps.
      tick += dt;
      while (tick >= 1 / 20) {
        tick -= 1 / 20;
        const rate = (0.12 * density) / 20;
        for (let col = 0; col < cols; col++) {
          const drift = 0.4 + 1.2 * noise3(col * 0.05 + time * 0.02, 1, 3);
          const face = key(col, open[col]!);
          // A full pile catches less: the wind takes what lands on it.
          const full = smoothstep(0.7, 1, depth[face]! / limitOf(face));
          deposit(face, rate * drift * (1 - full));
        }
        settle();
        if (breath > 0.05) melt();
      }
    },
    press() {
      shake();
    },
    draw(surface: GlyphSurface) {
      const { cols, rows } = grid;
      if (!cols) return;

      // The letters: solid lit blocks, bevelled by the slope of the softened mask.
      for (let row = 0; row < rows; row++) {
        for (let col = 0; col < cols; col++) {
          const i = row * cols + col;
          const m = mask[i]!;
          if (m < 0.12) continue;
          const tone = LETTER + hue[i]!;
          if (m < 0.5) {
            surface.put(col, row, ramp(EDGE, m * 2), tone, 0.5 + m * 0.5);
            continue;
          }
          const gx = (soft[i + 1] ?? 0) - (soft[i - 1] ?? 0);
          const gy = (soft[i + cols] ?? 0) - (soft[i - cols] ?? 0);
          const nx = -gx * 1.6;
          const ny = -gy * 1.6;
          const nl = Math.hypot(nx, ny, 1);
          const lit = (nx * LIGHT[0]! + ny * LIGHT[1]! + LIGHT[2]!) / nl;
          const light = smoothstep(0.1, 0.78, lit);
          surface.fill(col, row, tone, 0.5 + 0.5 * light);
          if (light < 0.6)
            surface.put(col, row, ramp(CUT, 1 - light / 0.6), DEEP, 0.25 + 0.3 * light);
        }
      }

      // Flakes, far ones first and behind the word.
      for (const f of flakes) {
        if (f.depth >= 0.4) continue;
        if (surface.filled(f.x, f.y)) continue;
        surface.put(f.x, f.y, DOT, SNOW, 0.16 + f.depth * 0.5);
      }

      drawPiles(surface);

      for (const c of clumps) {
        const fade = c.amount > 0 ? 0.85 : 0.6 * (1 - c.age / c.life);
        surface.put(c.x, c.y, c.amount > 0.25 ? '*' : DOT, SNOW, fade);
      }

      for (const f of flakes) {
        if (f.depth < 0.4) continue;
        const g = f.depth > 0.8 ? '*' : '+';
        surface.put(f.x, f.y, g, SNOW, f.depth > 0.8 ? 0.85 : 0.5);
      }
    },
  };

  /** The warm breath: snow near the pointer melts, and some of it blows away as powder. */
  function melt() {
    const { cols, aspect } = grid;
    for (const f of faces) {
      const d = depth[f]!;
      if (d < 0.05) continue;
      const col = f % cols;
      const top = Math.floor(f / cols) - d;
      const dist = Math.hypot(col + 0.5 - px, (top - py) * aspect);
      if (dist > 10) continue;
      const k = (1 - dist / 10) * breath;
      depth[f] = Math.max(0, d - k * 0.12);
      if (Math.random() < k * 0.15) {
        const dx = col + 0.5 - px;
        puff(col + 0.5, top, 1, Math.sign(dx) * 6, -1);
      }
    }
  }

  function drawPiles(surface: GlyphSurface) {
    const { cols } = grid;
    for (const f of faces) {
      // Cells at least half full: crisp steps read cleaner than half-lit blocks.
      const n = Math.round(depth[f]!);
      if (n < 1) continue;
      const col = f % cols;
      const row = Math.floor(f / cols);
      for (let k = 0; k < n; k++) {
        const r = row - n + k;
        // Lit on top, shading into the pile.
        surface.fill(col, r, SNOW, Math.max(0.5, 0.95 - k * 0.13));
        if (k > 1 && hash3(col, r, 13) < 0.1) surface.put(col, r, DOT, DEEP, 0.3);
      }
    }
  }
}
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;
}
components/lilt/ascii/more-scenes/shared.tsascii-scenes-kit

shared.ts

import { clamp } from '../engine/noise';

/**
 * How much of a cell a shape covers, from its signed distance in square units (negative inside).
 * The soft band is a little over a cell, so edges step down through lighter glyphs.
 */
export const coverage = (d: number) => clamp(0.5 - d / 1.3, 0, 1);

/** Parses `#rgb` or `#rrggbb` into channels; anything else reads as mid grey. */
export function rgb(hex: string): [number, number, number] {
  let h = hex.trim().replace('#', '');
  if (h.length === 3) h = h.replace(/./g, (c) => c + c);
  const n = parseInt(h.slice(0, 6), 16);
  if (!/^[0-9a-f]{6}/i.test(h) || Number.isNaN(n)) return [128, 128, 128];
  return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
}

/** `count` colours spaced evenly along a gradient through `stops`, as hex. */
export function gradient(stops: readonly string[], count: number): string[] {
  const channels = stops.map(rgb);
  if (channels.length === 0) channels.push([128, 128, 128]);
  return Array.from({ length: count }, (_, i) => {
    const t = count === 1 ? 0 : (i / (count - 1)) * (channels.length - 1);
    const k = Math.min(channels.length - 2, Math.floor(t));
    const a = channels[Math.max(0, k)]!;
    const b = channels[Math.max(0, k) + 1] ?? a;
    const f = channels.length === 1 ? 0 : t - Math.max(0, k);
    const c = a.map((v, j) => Math.round(v + (b[j]! - v) * f));
    return `#${c.map((v) => v.toString(16).padStart(2, '0')).join('')}`;
  });
}

/**
 * Rasterises a word into a coverage mask at grid resolution: 0 outside the letters, 1 inside, and
 * the share covered on their edges. Cells are taller than wide, so the word is drawn squashed into
 * rows and keeps its proportions on screen. Returns null where there is no canvas, such as on a
 * server or in tests, so the scene can carry on without the word.
 */
export function rasteriseWord(
  text: string,
  cols: number,
  rows: number,
  aspect: number,
  box: { x: number; y: number; width: number; height: number },
  weight = 800,
  align: 'center' | 'bottom' = 'center',
): Float32Array | null {
  if (!text.trim() || cols < 4 || rows < 4) return null;
  if (typeof document === 'undefined') return null;
  const canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d', { willReadFrequently: true });
  if (!ctx) return null;
  // Four samples a cell across and down, averaged back down to one value a cell.
  const ss = 4;
  canvas.width = cols * ss;
  canvas.height = rows * ss;
  const family = '"Helvetica Neue", Arial, "Segoe UI", system-ui, sans-serif';
  // Measured in square units (cell widths), then squashed by the aspect into rows.
  let size = 100;
  ctx.font = `${weight} ${size}px ${family}`;
  const measured = ctx.measureText(text);
  const glyphHeight =
    (measured.actualBoundingBoxAscent || size * 0.72) + (measured.actualBoundingBoxDescent || 0);
  size = Math.min((box.width / measured.width) * size, (box.height / glyphHeight) * size);
  ctx.setTransform(ss, 0, 0, ss / aspect, 0, 0);
  ctx.font = `${weight} ${size}px ${family}`;
  const m = ctx.measureText(text);
  const ascent = m.actualBoundingBoxAscent || size * 0.72;
  const descent = m.actualBoundingBoxDescent || 0;
  const left = box.x + (box.width - m.width) / 2;
  const top =
    align === 'bottom'
      ? box.y + box.height - descent
      : box.y + (box.height - ascent - descent) / 2 + ascent;
  ctx.fillStyle = '#fff';
  ctx.textBaseline = 'alphabetic';
  ctx.fillText(text, left, top);
  const data = ctx.getImageData(0, 0, canvas.width, canvas.height).data;
  const mask = new Float32Array(cols * rows);
  for (let row = 0; row < rows; row++) {
    for (let col = 0; col < cols; col++) {
      let sum = 0;
      for (let y = 0; y < ss; y++) {
        const base = ((row * ss + y) * canvas.width + col * ss) * 4 + 3;
        for (let x = 0; x < ss; x++) sum += data[base + x * 4]!;
      }
      mask[row * cols + col] = sum / (ss * ss * 255);
    }
  }
  return mask;
}

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.

Props10

Every option.

Pass these directly to AsciiSnow.

PropTypeDefaultWhat it does
mask(cols, rows, aspect) => Float32Array | null—A coverage mask for the word, one value a cell, for hosts without a canvas to draw text on.
textstring'winter'A word standing in the snow, which catches it on its letters. Empty for none.
colorsstring[]['#8b6cff', '#e5489c']Colours of the letters, left to right.
snowstring'#d6e0f2'Colour of the snow: a cool white that also shows on a light page.
densitynumber1How hard it snows.
windnumber1.5The steady wind, in columns a second. Gusts come and go around it.
cellSizenumber14Font size of each cell in pixels. Smaller cells draw a finer picture.
speednumber1How fast the clock runs: 0.5 is half speed, 2 is double.
interactivebooleantrueFollow the pointer and answer clicks.
labelstring—Describes the picture for screen readers. Without one it is a hidden background.
Previous sceneMeadowNext sceneBonsai

Ready when your data is. Start with one install.

Install a package, import the stylesheet once, and drop in a card or a scene.

Read the guideRead the guideView on GitHubView on GitHub
ChartsAll chartsAll chartsFinanceFinanceCustomizeCustomizeFeaturesFeatures
ComponentsAll componentsAll componentsAIAIStatusStatusActionsActionsDataData
VisualsAll visualsAll visualsAIAIDataDataSecuritySecurityProductProduct
ASCIIAll scenesAll scenesTextTextInterfaceInterfaceBackgroundsBackgroundsMediaMediaDataData
DocsGetting startedGetting startedAPI referenceAPI referenceMotion & accessibilityMotion & accessibilityllms.txtllms.txt
React components with a little lilt.GitHubGitHubnpmnpm