# Integrate `Dither` from Motion Garden

You are helping me add the **Dither** component to an existing project.
Everything you need is below — full source, dependencies, props and the
behavioural contract. Read it all before writing anything.

- **Component:** Dither
- **Category:** Backgrounds
- **Summary:** A live field crushed to one bit through an ordered threshold matrix. The only background here that looks better the cheaper it gets, and the only one that runs the same on a decade-old laptop as on a workstation.
- **Reference:** https://motion-garden.netlify.app/components/dither
- **Full catalog (for you, the agent):** https://motion-garden.netlify.app/llms.txt

## Stack this source assumes

- React 19 with the Next.js App Router (never the `pages/` directory)
- TypeScript, strict
- Tailwind CSS v4, CSS-first config (utilities are inline; no `tailwind.config` needed)

If my project differs, adapt the integration — but do not rewrite the animation math to suit a different stack. Ask me first.

## Dependencies

```bash
bun add ogl
```

## Files to create

2 files — all of them are required. Paths are as shipped; the component may live anywhere in my project, but keep every peer file at the exact path shown so the import aliases resolve.

### 1. `components/registry/dither/dither.tsx`

```tsx
"use client";

import { memo, useEffect, useRef, useState } from "react";
import { Renderer, Program, Mesh, Triangle } from "ogl";
import { useAnimationLoop, type Metrics } from "@/hooks/use-animation-loop";

export type DitherPattern = "bayer2" | "bayer4" | "bayer8" | "halftone" | "noise";
export type DitherField = "plasma" | "ridges" | "tunnel" | "drift";

interface DitherProps {
  pattern?: DitherPattern;
  levels?: number;
  pixelSize?: number;
  field?: DitherField;
  fieldSpeed?: number;
  fieldScale?: number;
  frameHold?: number;
  contrast?: number;
  inkColor?: string;
  paperColor?: string;
  paused?: boolean;
  reducedMotion?: boolean;
  className?: string;
}

const PATTERN_ID: Record<string, number> = {
  bayer2: 0,
  bayer4: 1,
  bayer8: 2,
  halftone: 3,
  noise: 4,
};
const FIELD_ID: Record<string, number> = {
  plasma: 0,
  ridges: 1,
  tunnel: 2,
  drift: 3,
};

const hexToRgb01 = (hex: string): [number, number, number] => {
  const h = hex.replace("#", "");
  const full = h.length === 3 ? h.split("").map((c) => c + c).join("") : h;
  const n = parseInt(full, 16);
  if (Number.isNaN(n) || full.length !== 6) return [1, 1, 1];
  return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255];
};

const supportsWebGL2 = () => {
  try {
    return !!document.createElement("canvas").getContext("webgl2");
  } catch {
    return false;
  }
};

const vertex = `#version 300 es
in vec2 position;
void main() { gl_Position = vec4(position, 0.0, 1.0); }`;

const fragment = `#version 300 es
precision highp float;
out vec4 fragColor;

uniform vec2  uResolution;
uniform float uDpr;
uniform vec3  uPhase;
uniform float uPattern;
uniform float uLevels;
uniform float uPixelSize;
uniform float uField;
uniform float uFieldScale;
uniform float uContrast;
uniform vec3  uInk;
uniform vec3  uPaper;

// Bayer by recursion. The 2x2 case is a closed form, and each larger matrix is
// the next coarser one scaled into the gaps of this one - which is the actual
// definition of an ordered dither matrix, not an approximation of it.
float bayer2(vec2 a) { a = floor(a); return fract(a.x * 0.5 + a.y * a.y * 0.75); }
float bayer4(vec2 a) { return bayer2(a * 0.5) * 0.25 + bayer2(a); }
float bayer8(vec2 a) { return bayer4(a * 0.5) * 0.25 + bayer2(a); }

// Interleaved gradient noise. Not true blue noise - that needs a baked texture -
// but it is the standard cheap stand-in and it carries the property that matters
// here: no lattice, so no fixed pattern for the eye to lock onto.
float ign(vec2 p) {
  return fract(52.9829189 * fract(dot(p, vec2(0.06711056, 0.00583715))));
}

// Clustered dot on a grid rotated 45 degrees, which is where a press puts the
// black screen: at 45 the rosette stops competing with the horizontal and
// vertical edges that dominate most images.
float halftone(vec2 p) {
  vec2 r = vec2(p.x - p.y, p.x + p.y) * 0.70710678;
  vec2 cell = fract(r) - 0.5;
  return clamp(length(cell) * 1.41421356, 0.0, 1.0);
}

float thresholdAt(vec2 cell) {
  if (uPattern < 0.5) return bayer2(cell);
  if (uPattern < 1.5) return bayer4(cell);
  if (uPattern < 2.5) return bayer8(cell);
  if (uPattern < 3.5) return halftone(cell * 0.25);
  return ign(cell);
}

float hash21(vec2 p) {
  p = fract(p * vec2(127.1, 311.7));
  p += dot(p, p + 34.56);
  return fract(p.x * p.y);
}

float vnoise(vec2 p) {
  vec2 i = floor(p), f = fract(p);
  vec2 u = f * f * (3.0 - 2.0 * f);
  return mix(
    mix(hash21(i), hash21(i + vec2(1.0, 0.0)), u.x),
    mix(hash21(i + vec2(0.0, 1.0)), hash21(i + vec2(1.0, 1.0)), u.x),
    u.y
  );
}

float fbm(vec2 p) {
  float a = 0.5, s = 0.0;
  for (int i = 0; i < 5; i++) { s += a * vnoise(p); p *= 2.02; a *= 0.5; }
  return s;
}

float fieldAt(vec2 p) {
  vec3 ph = uPhase;
  if (uField < 0.5) {
    float v = sin(p.x * 1.7 + ph.x) * cos(p.y * 1.3 + ph.y);
    v += sin(length(p) * 2.2 - ph.z) * 0.8;
    return v * 0.35 + 0.5;
  }
  if (uField < 1.5) {
    vec2 q = p + vec2(cos(ph.x), sin(ph.y)) * 0.8;
    float r = 1.0 - abs(fbm(q) * 2.0 - 1.0);
    return r * r;
  }
  if (uField < 2.5) {
    float r = max(length(p), 0.08);
    float a = atan(p.y, p.x);
    // The phase multiplier is an integer so the 2*PI wrap stays invisible: sin
    // steps by a whole number of turns and lands exactly where it left.
    return 0.5 + 0.5 * sin(2.4 / r - ph.x * 3.0 + a * 2.0);
  }
  vec2 w = vec2(fbm(p + ph.xy), fbm(p + ph.yz + 5.2));
  return fbm(p + w * 0.9);
}

void main() {
  float cellPx = max(uPixelSize, 1.0) * uDpr;
  vec2 cell = floor(gl_FragCoord.xy / cellPx);

  vec2 res = uResolution / uDpr;
  // Centre of this cell, in CSS pixels. Every pixel in the cell resolves to the
  // same sample, so the cell is one tone rather than a smear the grid then cuts.
  vec2 sp = (cell * cellPx + cellPx * 0.5) / uDpr;
  vec2 p = (sp - res * 0.5) / max(res.y, 1.0) * max(uFieldScale, 0.05);

  float v = clamp(fieldAt(p), 0.0, 1.0);
  v = clamp((v - 0.5) * uContrast + 0.5, 0.0, 1.0);

  float n = max(uLevels - 1.0, 1.0);
  // The threshold is offset to zero-mean and spread across exactly one
  // quantisation step. Any wider and the dither reads as noise laid over the
  // image; any narrower and it stops breaking up the bands it exists to break.
  float t = thresholdAt(cell) - 0.5;
  float q = clamp(floor(v * n + t + 0.5) / n, 0.0, 1.0);

  fragColor = vec4(mix(uPaper, uInk, q), 1.0);
}`;

const RATES = [0.31, 0.19, 0.11];
const TAU = Math.PI * 2;

const Dither = memo(
  ({
    pattern = "bayer8",
    levels = 2,
    pixelSize = 3,
    field = "plasma",
    fieldSpeed = 0.3,
    fieldScale = 2.4,
    frameHold = 0,
    contrast = 1,
    inkColor = "#e8e4d8",
    paperColor = "#0b0b0d",
    paused = false,
    reducedMotion = false,
    className,
  }: DitherProps) => {
    const containerRef = useRef<HTMLDivElement>(null);
    const drawRef = useRef<((dt: number) => void | false) | null>(null);
    const measureRef = useRef<((m: Metrics) => void) | null>(null);
    const glRef = useRef<WebGLRenderingContext | WebGL2RenderingContext | null>(null);

    const [fallback, setFallback] = useState(false);

    const loop = useAnimationLoop({
      target: containerRef,
      halted: paused || reducedMotion,
      dpr: "auto",
      onResize: (metrics) => measureRef.current?.(metrics),
      onFrame: ({ dt }) => (drawRef.current ? drawRef.current(dt) : false),
      gl: () => glRef.current,
    });

    const live = useRef({
      pattern, levels, pixelSize, field, fieldSpeed, fieldScale,
      frameHold, contrast, inkColor, paperColor,
    });
    live.current = {
      pattern, levels, pixelSize, field, fieldSpeed, fieldScale,
      frameHold, contrast, inkColor, paperColor,
    };

    useEffect(() => {
      const container = containerRef.current;
      if (fallback || !container) return;
      if (!supportsWebGL2()) {
        setFallback(true);
        return;
      }

      const renderer = new Renderer({
        webgl: 2,
        alpha: false,
        antialias: false,
        powerPreference: "high-performance",
        dpr: Math.min(window.devicePixelRatio || 1, 2),
      });
      const gl = renderer.gl;
      glRef.current = gl;

      const canvas = gl.canvas as HTMLCanvasElement;
      canvas.style.display = "block";
      canvas.style.position = "absolute";
      canvas.style.top = "0";
      canvas.style.left = "0";
      container.appendChild(canvas);

      const program = new Program(gl, {
        vertex,
        fragment,
        uniforms: {
          uResolution: { value: new Float32Array([1, 1]) },
          uDpr: { value: 1 },
          uPhase: { value: new Float32Array([0, 0, 0]) },
          uPattern: { value: PATTERN_ID[pattern] ?? 2 },
          uLevels: { value: levels },
          uPixelSize: { value: pixelSize },
          uField: { value: FIELD_ID[field] ?? 0 },
          uFieldScale: { value: fieldScale },
          uContrast: { value: contrast },
          uInk: { value: new Float32Array(hexToRgb01(inkColor)) },
          uPaper: { value: new Float32Array(hexToRgb01(paperColor)) },
        },
      });
      const mesh = new Mesh(gl, { geometry: new Triangle(gl), program });
      const u = program.uniforms as Record<string, { value: number | Float32Array }>;

      const phase = new Float32Array([0, 1.7, 4.1]);

      const sync = () => {
        const l = live.current;
        (u.uPhase.value as Float32Array).set(phase);
        u.uPattern.value = PATTERN_ID[l.pattern] ?? 2;
        u.uLevels.value = l.levels;
        u.uPixelSize.value = l.pixelSize;
        u.uField.value = FIELD_ID[l.field] ?? 0;
        u.uFieldScale.value = l.fieldScale;
        u.uContrast.value = l.contrast;
        (u.uInk.value as Float32Array).set(hexToRgb01(l.inkColor));
        (u.uPaper.value as Float32Array).set(hexToRgb01(l.paperColor));
      };

      let accrued = 0;
      let held = 0;

      drawRef.current = (dt) => {
        const l = live.current;
        accrued += dt;
        if (held <= 0) {
          for (let i = 0; i < 3; i++) {
            phase[i] = (phase[i] + accrued * RATES[i] * l.fieldSpeed) % TAU;
          }
          accrued = 0;
          held = Math.max(0, Math.round(l.frameHold));
        } else {
          held -= 1;
        }
        sync();
        renderer.render({ scene: mesh });
      };

      measureRef.current = ({ width, height, dpr }) => {
        renderer.dpr = dpr;
        renderer.setSize(Math.max(1, Math.floor(width)), Math.max(1, Math.floor(height)));
        const res = u.uResolution.value as Float32Array;
        res[0] = gl.drawingBufferWidth;
        res[1] = gl.drawingBufferHeight;
        u.uDpr.value = dpr;
        sync();
        renderer.render({ scene: mesh });
      };

      loop.resize();
      loop.start();

      return () => {
        drawRef.current = null;
        measureRef.current = null;
        if (container.contains(canvas)) container.removeChild(canvas);
      };
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [fallback]);

    useEffect(() => {
      loop.paint();
    }, [
      pattern, levels, pixelSize, field, fieldSpeed, fieldScale,
      frameHold, contrast, inkColor, paperColor, loop,
    ]);

    if (fallback) {
      const s = Math.max(pixelSize, 1) * 2;
      return (
        <div
          className={className ?? "relative h-full w-full overflow-hidden"}
          style={{
            backgroundColor: paperColor,
            backgroundImage: `repeating-conic-gradient(${inkColor} 0% 25%, ${paperColor} 0% 50%)`,
            backgroundSize: `${s}px ${s}px`,
            opacity: 0.9,
          }}
        />
      );
    }

    return (
      <div
        ref={containerRef}
        className={className ?? "relative h-full w-full overflow-hidden"}
      />
    );
  },
);

Dither.displayName = "Dither";

export default Dither;
```

### 2. `hooks/use-animation-loop.ts` — peer hook, required

```tsx
"use client";

import { useCallback, useEffect, useLayoutEffect, useMemo, useRef } from "react";

export interface Metrics {
  width: number;
  height: number;
  dpr: number;
  bufferWidth: number;
  bufferHeight: number;
}

export interface FrameInfo {
  now: number;
  dt: number;
  elapsed: number;
  frame: number;
}

export interface AnimationLoopHandle {
  start(): void;
  stop(): void;
  paint(): void;
  resize(): void;
  readonly running: boolean;
}

export interface AnimationLoopOptions {
  target: React.RefObject<HTMLElement | null>;
  halted?: boolean;
  dpr?: number | "auto";
  onResize?(metrics: Metrics): void;
  onFrame?(info: FrameInfo): void | false;
  paintWhenHalted?: boolean;
  resizeDebounceMs?: number;
  gl?(): WebGLRenderingContext | WebGL2RenderingContext | null | undefined;
  onDispose?(): void;
  deps?: unknown[];
}

const MAX_DT = 1 / 15;

export function useAnimationLoop(
  options: AnimationLoopOptions,
): AnimationLoopHandle {
  const opts = useRef(options);
  useLayoutEffect(() => {
    opts.current = options;
  });

  const raf = useRef<number | null>(null);
  const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
  const running = useRef(false);
  const disposed = useRef(false);
  const startedAt = useRef(0);
  const last = useRef(0);
  const frame = useRef(0);

  const measure = useCallback((): Metrics | null => {
    const el = opts.current.target.current;
    if (!el) return null;
    const rect = el.getBoundingClientRect();
    const cap = opts.current.dpr ?? "auto";
    const limit = cap === "auto" ? 2 : cap;
    const dpr = Math.min(
      typeof window === "undefined" ? 1 : window.devicePixelRatio || 1,
      limit,
    );
    return {
      width: rect.width,
      height: rect.height,
      dpr,
      bufferWidth: Math.max(1, Math.round(rect.width * dpr)),
      bufferHeight: Math.max(1, Math.round(rect.height * dpr)),
    };
  }, []);

  const tick = useCallback(function tick(now: number) {
    if (disposed.current) return;

    if (startedAt.current === 0) startedAt.current = now;
    const dt = last.current === 0 ? 0 : Math.min((now - last.current) / 1000, MAX_DT);
    last.current = now;

    const info: FrameInfo = {
      now,
      dt,
      elapsed: (now - startedAt.current) / 1000,
      frame: frame.current++,
    };

    const verdict = opts.current.onFrame?.(info);

    if (disposed.current) return;

    if (verdict === false || opts.current.halted) {
      running.current = false;
      raf.current = null;
      return;
    }
    raf.current = requestAnimationFrame(tick);
  }, []);

  const start = useCallback(() => {
    if (disposed.current || running.current) return;
    running.current = true;
    last.current = 0;
    raf.current = requestAnimationFrame(tick);
  }, [tick]);

  const stop = useCallback(() => {
    running.current = false;
    if (raf.current !== null) {
      cancelAnimationFrame(raf.current);
      raf.current = null;
    }
  }, []);

  const paint = useCallback(() => start(), [start]);

  const resize = useCallback(() => {
    const metrics = measure();
    if (!metrics) return;
    opts.current.onResize?.(metrics);
    if (opts.current.paintWhenHalted !== false) paint();
    else if (!opts.current.halted) start();
  }, [measure, paint, start]);

  const deps = options.deps ?? [];

  useEffect(() => {
    disposed.current = false;
    const el = opts.current.target.current;
    if (!el) return;

    const run = () => {
      if (disposed.current) return;
      resize();
    };

    const observer = new ResizeObserver(() => {
      const wait = opts.current.resizeDebounceMs ?? 0;
      if (wait <= 0) {
        run();
        return;
      }
      if (timer.current !== null) clearTimeout(timer.current);
      timer.current = setTimeout(() => {
        timer.current = null;
        run();
      }, wait);
    });
    observer.observe(el);

    resize();
    if (!opts.current.halted) start();

    return () => {
      disposed.current = true;
      running.current = false;
      if (raf.current !== null) {
        cancelAnimationFrame(raf.current);
        raf.current = null;
      }
      if (timer.current !== null) {
        clearTimeout(timer.current);
        timer.current = null;
      }
      observer.disconnect();
      opts.current.onDispose?.();
      const context = opts.current.gl?.();
      context?.getExtension("WEBGL_lose_context")?.loseContext();
      startedAt.current = 0;
      last.current = 0;
      frame.current = 0;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, deps);

  const halted = options.halted ?? false;
  useEffect(() => {
    if (!halted) start();
  }, [halted, start]);

  return useMemo<AnimationLoopHandle>(
    () => ({
      start,
      stop,
      paint,
      resize,
      get running() {
        return running.current;
      },
    }),
    [start, stop, paint, resize],
  );
}
```


## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `pattern` | `"bayer2" | "bayer4" | "bayer8" | "halftone" | "noise"` | `"bayer8"` | Which threshold matrix decides each cell. Bayer is the ordered one — a fixed lattice, so the texture is stable and never crawls between frames. Halftone rotates the grid forty-five degrees and clusters instead of scattering, which is what a printing press does. Noise drops the lattice entirely and pays for it with a pattern that shimmers the moment anything moves. |
| `levels` | `number` | `2` | Tones per channel after quantisation. Two is the honest one-bit case. Above four this stops being dithering and starts being a slightly cheap gradient — worth dragging once to see exactly where the effect stops earning its name. Range 2–8. |
| `pixelSize` | `number` | `3` | Size of one dither cell, held in CSS pixels rather than device pixels. Held in device pixels the grid would halve on a retina screen and the effect would vanish on exactly the displays people judge it on. Range 1–12 px. |
| `field` | `"plasma" | "ridges" | "tunnel" | "drift"` | `"plasma"` | What is being quantised underneath. The dither is indifferent to it — that is the point of a threshold matrix — but the four differ sharply in how much smooth gradient they hand it, and a pattern only shows its character on a gradient. |
| `fieldSpeed` | `number` | `0.3` | Rate the field evolves. At zero it parks, which is the clearest way to see the threshold matrix itself rather than the image passing through it. Range 0–2 ×. |
| `fieldScale` | `number` | `2.4` | Size of the field's features relative to the container. Small enough and the whole panel is one tone with nothing for the dither to resolve; large enough and every cell disagrees with its neighbour and the pattern turns to static. Range 0.5–8. |
| `frameHold` | `number` | `0` | How many frames the field is held before it advances. Zero runs at display rate; three gives the deliberate stutter of a machine that could not keep up. The frame is still drawn either way and the held time is spent in one go when the hold expires — so this is a look, not a saving, and not a speed control in disguise. Range 0–8 frames. |
| `contrast` | `number` | `1` | Contrast applied around mid-grey before quantisation. This is the real control over how much of the field survives: at two levels there is exactly one threshold, so pushing contrast up does not brighten the image, it decides where the edge between black and white falls. Range 0.2–3. |
| `inkColor` | `string (hex)` | `"#e8e4d8"` | The colour a lit cell takes. Warm off-white rather than pure white on purpose — a true #ffffff against near-black is the one pairing that makes the grid buzz. |
| `paperColor` | `string (hex)` | `"#0b0b0d"` | The colour an unlit cell takes. |

## Usage

```tsx
import Dither from "@/components/registry/dither/dither";

<Dither
  pattern="bayer8"
  levels={2}
  pixelSize={3}
  field="plasma"
  fieldSpeed={0.3}
  fieldScale={2.4}
  frameHold={0}
  contrast={1}
  inkColor="#e8e4d8"
  paperColor="#0b0b0d"
/>
```

The import path matches the file path above; change it if you move the component. Every value shown is the documented default — pass only what you actually want to change. The snippet lists the tunable props only: if the component's props type in the source requires others (content, handlers, data), pass those too.

## Integration rules

- Keep the `"use client"` directive. This is a client component and will not render as a Server Component.
- It fills its parent. Give the wrapper an explicit height (or a definite grid area) — against a height-auto parent it collapses to nothing.
- It takes a `reducedMotion` prop and quiesces when true. Wire it to a `prefers-reduced-motion` listener rather than hardcoding `false`.
- It runs a free-running animation loop. Halt it when off-screen or backgrounded if you care about battery.
- The peer hook is required, not optional. Copy it to `hooks/use-animation-loop.ts` so the component's `@/hooks/use-animation-loop` import resolves.
- It owns a GPU/canvas context and releases it on unmount. Preserve the cleanup return — leaking contexts kills the tab after a few navigations.

## Your task

1. Tell me where in my project this should live and why.
2. Create the files above verbatim.
3. Wire the component into the place I point you at, with sensible props for that context.
4. Flag anything in my setup that conflicts with the stack assumptions above.

Do not restyle the component or alter the animation math unless I ask.
