Skip to content
Charts55Components12Visuals14ASCII45
GitHubGet startedGet started
All ASCIIDissolve imageInterface
PreviousNext: Scroll meter

Move over the picture to dissolve it around the pointer. Change the duration to watch it arrive again.

Dissolve image

Interface

An image that arrives out of type: glyphs in the picture’s own colours give way to the picture in drifting patches. Afterwards the pointer turns it back into type.

Customize 5

1.8
10px
Install & copy sourceInstall & copy sourceSee propsSee props8

Live code

As tuned above.

Every control in the inspector updates this snippet directly. Defaults are omitted to keep your markup minimal.

example.tsx

import { AsciiDissolve } from '@/components/lilt/ascii/interface/ascii-dissolve';

export function Example() {
  return <AsciiDissolve />;
}

Installation6

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/dissolve.json
components/lilt/ascii/interface/ascii-dissolve.tsx

ascii-dissolve.tsx

'use client';

import { useEffect, useRef, type CSSProperties } from 'react';
import { noise3 } from '../engine/noise';
import { MONO_STACK, fitCanvas, useReducedMotion } from './motion';

export interface AsciiDissolveProps {
  /** The image: same origin, or served with CORS so its colours can be read. Without one, a painted sunset. */
  src?: string;
  /** Describes the image for screen readers. */
  alt?: string;
  /** When it resolves: the first time it scrolls into view, or at once. Default `view`. */
  trigger?: 'view' | 'mount';
  /** Seconds from all type to all picture. Default 1.8. */
  duration?: number;
  /** Font size of each cell of type, in pixels. Default 10. */
  cellSize?: number;
  /** The pointer turns the picture back into type around it. Default true. */
  hover?: boolean;
  /** Glyphs from sparse to dense. */
  characters?: string;
  /** `cover` fills the box and crops; `contain` shows all of it. Default `cover`. */
  fit?: 'cover' | 'contain';
  className?: string;
  style?: CSSProperties;
}

/** A sunset painted in the browser, for trying the effect with no image at all. */
function paintSunset(): HTMLCanvasElement {
  const c = document.createElement('canvas');
  c.width = 640;
  c.height = 400;
  const g = c.getContext('2d')!;
  const sky = g.createLinearGradient(0, 0, 0, 400);
  sky.addColorStop(0, '#2a1b6e');
  sky.addColorStop(0.45, '#c2408f');
  sky.addColorStop(0.75, '#ff9a5a');
  sky.addColorStop(1, '#ffd38a');
  g.fillStyle = sky;
  g.fillRect(0, 0, 640, 400);
  g.fillStyle = '#fff1c4';
  g.beginPath();
  g.arc(420, 250, 70, 0, Math.PI * 2);
  g.fill();
  const ridge = (base: number, height: number, color: string, seed: number) => {
    g.fillStyle = color;
    g.beginPath();
    g.moveTo(0, 400);
    for (let x = 0; x <= 640; x += 8)
      g.lineTo(
        x,
        base - Math.abs(Math.sin(x * 0.012 + seed) + Math.sin(x * 0.031 + seed * 2) * 0.5) * height,
      );
    g.lineTo(640, 400);
    g.fill();
  };
  ridge(330, 70, '#5b2a6e', 1);
  ridge(370, 60, '#2b1546', 3);
  ridge(400, 40, '#140b26', 5);
  return c;
}

/**
 * An image that arrives out of type. It starts as glyphs in the picture's own colours, and cell by
 * cell, in drifting patches, the glyphs give way to the picture itself. Afterwards the pointer
 * turns the picture back into type wherever it passes.
 */
export function AsciiDissolve({
  src,
  alt,
  trigger = 'view',
  duration = 1.8,
  cellSize = 10,
  hover = true,
  characters = ' .:-=+*#%@',
  fit = 'cover',
  className,
  style,
}: AsciiDissolveProps) {
  const ref = useRef<HTMLCanvasElement>(null);
  const reduced = useReducedMotion();
  const pointer = useRef({ x: -999, y: -999, on: 0, target: 0 });
  const wake = useRef<() => void>(() => undefined);

  useEffect(() => {
    const canvas = ref.current;
    const ctx = canvas?.getContext('2d');
    if (!canvas || !ctx) return;
    let picture: CanvasImageSource | null = null;
    let pw = 0;
    let ph = 0;
    // Colours a cell, read from a copy of the picture scaled down to one pixel a cell.
    let colours: Uint8ClampedArray | null = null;
    let cols = 0;
    let rows = 0;
    let start = -1;
    let raf = 0;
    let visible = trigger === 'mount';
    const set = characters.length > 1 ? characters : ' .:-=+*#%@';

    const place = (w: number, h: number) => {
      const scale = fit === 'cover' ? Math.max(w / pw, h / ph) : Math.min(w / pw, h / ph);
      const dw = pw * scale;
      const dh = ph * scale;
      return { x: (w - dw) / 2, y: (h - dh) / 2, w: dw, h: dh };
    };

    const sample = (w: number, h: number, cw: number, ch: number) => {
      cols = Math.ceil(w / cw);
      rows = Math.ceil(h / ch);
      const small = document.createElement('canvas');
      small.width = cols;
      small.height = rows;
      const sg = small.getContext('2d', { willReadFrequently: true });
      if (!sg || !picture) return;
      const box = place(w, h);
      sg.drawImage(picture, box.x / cw, box.y / ch, box.w / cw, box.h / ch);
      try {
        colours = sg.getImageData(0, 0, cols, rows).data;
      } catch {
        // A picture from another origin without CORS: its colours cannot be read.
        colours = null;
      }
    };

    const draw = (now: number) => {
      raf = 0;
      if (!picture) return;
      const box = canvas.getBoundingClientRect();
      const w = box.width;
      const h = box.height;
      const dpr = fitCanvas(canvas, w, h);
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
      ctx.font = `600 ${cellSize}px ${MONO_STACK}`;
      ctx.textBaseline = 'middle';
      ctx.textAlign = 'center';
      const cw = Math.max(4, ctx.measureText('M').width);
      const ch = cellSize * 1.2;
      if (!colours || Math.ceil(w / cw) !== cols || Math.ceil(h / ch) !== rows)
        sample(w, h, cw, ch);
      if (visible && start < 0) start = now;
      const progress = reduced
        ? 1
        : start < 0
          ? 0
          : Math.min(1, (now - start) / (Math.max(0.2, duration) * 1000));
      const p = pointer.current;
      p.on += (p.target - p.on) * 0.15;
      ctx.clearRect(0, 0, w, h);
      const placed = place(w, h);
      ctx.drawImage(picture, placed.x, placed.y, placed.w, placed.h);
      const ink = getComputedStyle(canvas).color;
      const tick = Math.floor(now / 80);
      for (let row = 0; row < rows; row++) {
        for (let col = 0; col < cols; col++) {
          // Cells give way in drifting patches, a little left to right.
          const threshold = 0.08 + noise3(col * 0.09, row * 0.14, 3) * 0.7 + (col / cols) * 0.18;
          let glyphness =
            progress >= 1 ? 0 : Math.max(0, Math.min(1, (threshold - progress) * 6 + 0.5));
          if (p.on > 0.01) {
            const d = Math.hypot(col * cw + cw / 2 - p.x, row * ch + ch / 2 - p.y) / (cw * 14);
            glyphness = Math.max(glyphness, (1 - d) * p.on * 1.4);
          }
          if (glyphness <= 0.02) continue;
          const i = (row * cols + col) * 4;
          const r = colours?.[i] ?? 128;
          const g = colours?.[i + 1] ?? 128;
          const b = colours?.[i + 2] ?? 128;
          // Behind a glyph, the picture's own colour in deep shadow, so type and picture belong together.
          if (colours) {
            ctx.globalAlpha = Math.min(1, glyphness) * 0.9;
            ctx.fillStyle = `rgb(${r * 0.22} ${g * 0.22} ${b * 0.22})`;
            ctx.fillRect(col * cw, row * ch, cw + 0.5, ch + 0.5);
          } else ctx.clearRect(col * cw, row * ch, cw + 0.5, ch + 0.5);
          const light = (0.3 * r + 0.59 * g + 0.11 * b) / 255;
          const flicker = glyphness < 0.9 ? ((col * 7 + row * 13 + tick) % 3) * 0.08 : 0;
          const glyph =
            set[Math.min(set.length - 1, Math.floor((light * 0.8 + 0.2 + flicker) * set.length))] ??
            '#';
          ctx.globalAlpha = Math.min(1, glyphness);
          ctx.fillStyle = colours ? `rgb(${r} ${g} ${b})` : ink;
          ctx.fillText(glyph, col * cw + cw / 2, row * ch + ch / 2);
        }
      }
      ctx.globalAlpha = 1;
      if ((progress < 1 && start >= 0) || p.on > 0.01 || p.target > 0)
        raf = requestAnimationFrame(draw);
    };
    wake.current = () => {
      if (!raf) raf = requestAnimationFrame(draw);
    };

    const ready = (image: CanvasImageSource, w: number, h: number) => {
      picture = image;
      pw = w;
      ph = h;
      colours = null;
      wake.current();
    };
    if (src) {
      const img = new Image();
      img.crossOrigin = 'anonymous';
      img.onload = () => ready(img, img.naturalWidth, img.naturalHeight);
      img.src = src;
    } else {
      const painted = paintSunset();
      ready(painted, painted.width, painted.height);
    }

    let observer: IntersectionObserver | null = null;
    if (!visible && typeof IntersectionObserver !== 'undefined') {
      observer = new IntersectionObserver(
        (entries) => {
          if (entries.some((e) => e.isIntersecting)) {
            visible = true;
            observer?.disconnect();
            wake.current();
          }
        },
        { threshold: 0.3 },
      );
      observer.observe(canvas);
    } else visible = true;
    const resize = new ResizeObserver(() => wake.current());
    resize.observe(canvas);
    return () => {
      cancelAnimationFrame(raf);
      observer?.disconnect();
      resize.disconnect();
    };
  }, [src, trigger, duration, cellSize, characters, fit, reduced]);

  return (
    <canvas
      ref={ref}
      className={className}
      role={alt ? 'img' : undefined}
      aria-label={alt}
      aria-hidden={alt ? undefined : true}
      style={{ display: 'block', width: '100%', height: '100%', ...style }}
      onPointerMove={(event) => {
        if (!hover || reduced) return;
        const box = event.currentTarget.getBoundingClientRect();
        pointer.current.x = event.clientX - box.left;
        pointer.current.y = event.clientY - box.top;
        pointer.current.target = 1;
        wake.current();
      }}
      onPointerLeave={() => {
        pointer.current.target = 0;
        wake.current();
      }}
    />
  );
}
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/interface/motion.tsascii-motion

motion.ts

import { useEffect, useState } from 'react';

/** True when the reader asks for less motion. False on the server and before the first effect. */
export function useReducedMotion() {
  const [reduced, setReduced] = useState(false);
  useEffect(() => {
    if (typeof window.matchMedia !== 'function') return;
    const query = window.matchMedia('(prefers-reduced-motion: reduce)');
    const update = () => setReduced(query.matches);
    update();
    query.addEventListener('change', update);
    return () => query.removeEventListener('change', update);
  }, []);
  return reduced;
}

/**
 * Seconds since the clock started, re-rendering at most `fps` times a second while `running`.
 * Stopped, it costs nothing and holds its last value.
 */
export function useClock(running: boolean, fps = 30) {
  const [time, setTime] = useState(0);
  useEffect(() => {
    if (!running) return;
    let raf = 0;
    let last = -1;
    const start = performance.now();
    const tick = (now: number) => {
      // A frame's timestamp can fall a little before the clock started; time never runs back.
      const t = Math.max(0, (now - start) / 1000);
      const frame = Math.floor(t * fps);
      if (frame !== last) {
        last = frame;
        setTime(t);
      }
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [running, fps]);
  return time;
}

/** A monospace stack for components that set their own type. */
export const MONO_STACK =
  'ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace';

/**
 * The font a canvas overlay draws its glyphs in: the element's own family when it is monospace,
 * otherwise a monospace stack at the element's size, so glyphs always sit on a grid.
 */
export function monoFont(ctx: CanvasRenderingContext2D, element: Element, weight = 500) {
  const css = getComputedStyle(element);
  const size = parseFloat(css.fontSize) || 14;
  const own = `${weight} ${size}px ${css.fontFamily || 'monospace'}`;
  ctx.font = own;
  const mono = Math.abs(ctx.measureText('i').width - ctx.measureText('M').width) < 0.01;
  const font = mono ? own : `${weight} ${size}px ${MONO_STACK}`;
  ctx.font = font;
  return { font, size, cw: Math.max(4, ctx.measureText('M').width) };
}

/** Sizes a canvas's backing store to its box at the device's pixel ratio, capped at 2. */
export function fitCanvas(canvas: HTMLCanvasElement, width: number, height: number) {
  const dpr = Math.min(window.devicePixelRatio || 1, 2);
  const w = Math.max(1, Math.round(width * dpr));
  const h = Math.max(1, Math.round(height * dpr));
  if (canvas.width !== w) canvas.width = w;
  if (canvas.height !== h) canvas.height = h;
  return dpr;
}

/** Mixes two `#rrggbb` colours; anything else returns the nearer one unchanged. */
export function mixHex(a: string, b: string, t: number) {
  const pa = /^#([0-9a-f]{6})$/i.exec(a);
  const pb = /^#([0-9a-f]{6})$/i.exec(b);
  if (!pa || !pb) return t < 0.5 ? a : b;
  const na = parseInt(pa[1]!, 16);
  const nb = parseInt(pb[1]!, 16);
  const ch = (shift: number) =>
    Math.round(((na >> shift) & 255) * (1 - t) + ((nb >> shift) & 255) * t);
  return `#${((1 << 24) | (ch(16) << 16) | (ch(8) << 8) | ch(0)).toString(16).slice(1)}`;
}

Usage

How it behaves.

It fills its parent; give the parent a size. The picture’s pixels are read to colour the type, so it must come from the same origin or be served with CORS; otherwise the type takes the text colour and the picture still arrives. Give it an `alt` when the picture carries meaning.

Props8

Every option.

Pass these directly to AsciiDissolve.

PropTypeDefaultWhat it does
altstring—Describes the image for screen readers. Without one it is decorative.
trigger'view' | 'mount''view'When it resolves: the first time it scrolls into view, or at once.
charactersstring' .:-=+*#%@'Glyphs from sparse to dense.
srcstring''Same origin, or served with CORS. Empty paints a sunset in the browser.
durationnumber1.8Seconds from all type to all picture.
cellSizenumber10Font size of each cell of type, in pixels.
hoverbooleantrueTurn the picture back into type around the pointer.
fitstring'cover'Fill the box and crop, or show all of it.
Previous sceneGhost cursorsNext sceneScroll meter

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