Skip to content
Charts55Components12Visuals14ASCII45
GitHubGet startedGet started
All ASCIIGlitchText
PreviousNext: Counter
404

Hover the text to make it glitch.

Glitch

Text

Text that glitches now and then: slices slip, the colours split, a letter turns to a glyph.

Customize 3

0.50
4.0
Install & copy sourceInstall & copy sourceSee propsSee props4

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 { AsciiGlitch } from '@/components/lilt/ascii/text/ascii-glitch';

export function NotFound() {
  return (
    <main style={{ display: 'grid', placeItems: 'center', minHeight: '100vh' }}>
      <h1 style={{ margin: 0, fontSize: 160, fontWeight: 800 }}>
        <AsciiGlitch />
      </h1>
    </main>
  );
}

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/glitch.json
components/lilt/ascii/text/ascii-glitch.tsx

ascii-glitch.tsx

'use client';

import {
  createElement,
  useCallback,
  useEffect,
  useRef,
  useState,
  type CSSProperties,
  type ElementType,
} from 'react';
import { clamp } from '../engine/noise';
import { rand, useReducedMotion } from './text-kit';

export interface AsciiGlitchProps {
  /** The text. Default '404'. */
  text?: string;
  /** How hard it glitches, 0 to 1: how far slices slip and how many letters swap. Default 0.5. */
  intensity?: number;
  /** Seconds between glitches, give or take a little. 0 glitches only on hover. Default 4. */
  interval?: number;
  /** The element to render, such as 'h1'. Default 'span'. */
  as?: ElementType;
  className?: string;
  style?: CSSProperties;
}

const SWAPS = '#%&$@*/\\<>01';
const RED = '#ff3d6e';
const CYAN = '#22d3ee';
/** A burst is a few frames this far apart, each a new break. */
const FRAME_MS = 55;

interface Slice {
  top: number;
  bottom: number;
  shift: number;
}

interface Break {
  /** Colour split, in em. */
  split: number;
  slices: Slice[];
  text: string;
}

/** One frame of a glitch: where the text is cut, how far each slice slips, which letters swap. */
function breakOf(text: string, intensity: number, seed: number): Break {
  const r = (k: number) => rand(seed, k, 31);
  const split = (0.015 + 0.04 * intensity) * (r(0) < 0.5 ? -1 : 1);
  // Cut the height into bands; some slip sideways, most stay put.
  const cuts = [0, 100];
  const count = 1 + Math.round(1 + 3 * intensity * r(1));
  for (let i = 0; i < count; i++) cuts.push(Math.round(8 + r(2 + i) * 84));
  cuts.sort((a, b) => a - b);
  const slices: Slice[] = [];
  for (let i = 0; i < cuts.length - 1; i++) {
    const top = cuts[i]!;
    const bottom = cuts[i + 1]!;
    if (bottom - top < 2) continue;
    const moves = r(10 + i) < 0.45 + 0.3 * intensity;
    const shift = moves ? (r(20 + i) - 0.5) * 2 * (0.03 + 0.14 * intensity) : 0;
    // Neighbours that slip together are one slice: no seam between them.
    const prev = slices[slices.length - 1];
    if (prev && prev.shift === shift) prev.bottom = bottom;
    else slices.push({ top, bottom, shift });
  }
  // On some frames a letter or two turns into a glyph.
  const letters = Array.from(text);
  if (r(40) < 0.4 + 0.4 * intensity) {
    const swaps = Math.max(1, Math.round(letters.length * 0.2 * intensity));
    for (let i = 0; i < swaps; i++) {
      const at = Math.floor(r(50 + i) * letters.length);
      if (letters[at] !== ' ') letters[at] = SWAPS[Math.floor(r(60 + i) * SWAPS.length)]!;
    }
  }
  return { split, slices, text: letters.join('') };
}

const LAYER: CSSProperties = {
  position: 'absolute',
  inset: 0,
  whiteSpace: 'inherit',
  pointerEvents: 'none',
};

/**
 * Text that glitches now and then: slices of it slip sideways, it splits into red and cyan, and a
 * letter or two turns into a glyph, for a fraction of a second, then snaps back. It glitches on
 * hover too. The bursts are short and far apart; with reduced motion it never glitches.
 */
export function AsciiGlitch({
  text = '404',
  intensity = 0.5,
  interval = 4,
  as = 'span',
  className,
  style,
}: AsciiGlitchProps) {
  const [frameOf, setFrame] = useState<Break | null>(null);
  const reduced = useReducedMotion();
  const busy = useRef(false);
  const timers = useRef<ReturnType<typeof setTimeout>[]>([]);
  const strength = clamp(intensity, 0, 1);

  const later = (ms: number, fn: () => void) => {
    timers.current.push(setTimeout(fn, ms));
  };

  /** A burst: a few frames of breaks, then clean; now and then a quick second burst. */
  const burst = useCallback(
    (again = true) => {
      if (busy.current) return;
      busy.current = true;
      const frames = 2 + Math.round(2 + 3 * strength * Math.random());
      const seed = Math.floor(Math.random() * 1e6);
      for (let f = 0; f < frames; f++) {
        later(f * FRAME_MS, () => setFrame(breakOf(text, strength, seed + f)));
      }
      later(frames * FRAME_MS, () => {
        setFrame(null);
        busy.current = false;
        if (again && Math.random() < 0.35) later(90 + Math.random() * 120, () => burst(false));
      });
    },
    [text, strength],
  );

  // Glitches on a loose schedule, so it never settles into a beat.
  useEffect(() => {
    if (reduced || !(interval > 0)) return;
    let timer: ReturnType<typeof setTimeout>;
    const next = () => {
      timer = setTimeout(
        () => {
          burst();
          next();
        },
        interval * 1000 * (0.6 + 0.8 * Math.random()),
      );
    };
    next();
    return () => clearTimeout(timer);
  }, [reduced, interval, burst]);

  useEffect(
    () => () => {
      timers.current.forEach(clearTimeout);
      timers.current = [];
      busy.current = false;
    },
    [],
  );

  const onPointerEnter = () => {
    if (!reduced) burst();
  };

  const shown = reduced ? null : frameOf;
  const layer = (key: string, extra: CSSProperties, content: string) => (
    <span key={key} aria-hidden="true" style={{ ...LAYER, ...extra }}>
      {content}
    </span>
  );

  return createElement(
    as,
    {
      className,
      style: { position: 'relative', display: 'inline-block', ...style },
      onPointerEnter,
    },
    // The real text sizes the element and stays readable to screen readers; while glitching its
    // ink steps aside for the broken copies drawn over it.
    <span key="text" style={{ opacity: shown ? 0 : 1 }}>
      {text}
    </span>,
    shown && [
      layer(
        'red',
        { color: RED, opacity: 0.8, transform: `translateX(${-shown.split}em)` },
        shown.text,
      ),
      layer(
        'cyan',
        { color: CYAN, opacity: 0.8, transform: `translateX(${shown.split}em)` },
        shown.text,
      ),
      ...shown.slices.map((slice, i) =>
        layer(
          `s${i}`,
          {
            // Slices overlap by a hair so their anti-aliased edges never leave a seam.
            clipPath: `inset(calc(${slice.top}% - 0.5px) -1em calc(${100 - slice.bottom}% - 0.5px) -1em)`,
            transform: slice.shift ? `translateX(${slice.shift}em)` : undefined,
          },
          shown.text,
        ),
      ),
    ],
  );
}
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/text/text-kit.tsascii-text-kit

text-kit.ts

'use client';

import {
  useEffect,
  useState,
  useSyncExternalStore,
  type CSSProperties,
  type RefObject,
} from 'react';

/** Hides text from sight but keeps it for screen readers, copy and find-in-page. */
export const VISUALLY_HIDDEN: CSSProperties = {
  position: 'absolute',
  width: 1,
  height: 1,
  padding: 0,
  margin: -1,
  overflow: 'hidden',
  clip: 'rect(0 0 0 0)',
  clipPath: 'inset(50%)',
  whiteSpace: 'nowrap',
  border: 0,
};

/** Characters text scrambles through: code-like, so the decode reads as computing. */
export const CODE_GLYPHS = '01<>/\\{}[]#$%&*+=?~';

/** A stable pseudo-random number in [0, 1) for a pair of integers and a salt. */
export function rand(a: number, b: number, salt = 0): number {
  let h =
    Math.imul(a | 0, 0x27d4eb2d) ^ Math.imul(b | 0, 0x165667b1) ^ Math.imul(salt | 0, 0x9e3779b1);
  h = Math.imul(h ^ (h >>> 15), 0x85ebca6b);
  h = Math.imul(h ^ (h >>> 13), 0xc2b2ae35);
  return ((h ^ (h >>> 16)) >>> 0) / 4294967296;
}

const REDUCED = '(prefers-reduced-motion: reduce)';

function subscribeReduced(onChange: () => void) {
  if (typeof window === 'undefined' || !window.matchMedia) return () => undefined;
  const query = window.matchMedia(REDUCED);
  query.addEventListener?.('change', onChange);
  return () => query.removeEventListener?.('change', onChange);
}

const readReduced = () =>
  typeof window !== 'undefined' && !!window.matchMedia && window.matchMedia(REDUCED).matches;

/** True when the reader prefers reduced motion. False on the server. */
export function useReducedMotion(): boolean {
  return useSyncExternalStore(subscribeReduced, readReduced, () => false);
}

/**
 * Becomes true the first time the element scrolls into view, and stays true. Without an
 * IntersectionObserver (old browsers, tests) it is true at once.
 */
export function useSeen(ref: RefObject<Element | null>, enabled = true): boolean {
  const [seen, setSeen] = useState(false);
  useEffect(() => {
    if (!enabled || seen) return;
    const el = ref.current;
    if (!el || typeof IntersectionObserver === 'undefined') {
      setSeen(true);
      return;
    }
    const observer = new IntersectionObserver(
      (entries) => {
        if (entries.some((entry) => entry.isIntersecting)) {
          setSeen(true);
          observer.disconnect();
        }
      },
      { threshold: 0.35 },
    );
    observer.observe(el);
    return () => observer.disconnect();
  }, [ref, enabled, seen]);
  return seen;
}

/** requestAnimationFrame, or a 60 Hz timer where there is none. Returns a cancel function. */
export function frame(callback: (now: number) => void): () => void {
  if (typeof requestAnimationFrame === 'function') {
    const id = requestAnimationFrame(callback);
    return () => cancelAnimationFrame(id);
  }
  const id = setTimeout(() => callback(performance.now()), 16);
  return () => clearTimeout(id);
}

Usage

How it behaves.

It is real text in the font, size and colour around it. Each glitch is a burst of a few frames, a fraction of a second long, then the text snaps back; the gaps between them vary so it never falls into a beat. With reduced motion it never glitches.

Props4

Every option.

Pass these directly to AsciiGlitch.

PropTypeDefaultWhat it does
asElementType'span'The element to render, such as 'h1' or 'p'.
textstring'404'The text.
intensitynumber0.5How far slices slip, how wide the colours split and how many letters swap.
intervalnumber4Seconds between glitches, give or take. 0 glitches only on hover.
Previous sceneFlagNext sceneCounter

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