Dither cursor trail
The background effect from Alert's home page: a trail of ordered-dither pixels that follows the pointer and keeps sliding after it stops.
Build a React 19 + TypeScript component called DitherCursor: a cursor effect from Alert's home page. A trail of ordered-dither pixels follows the pointer, keeps its momentum and fades, behind a short headline. Constraints: one .tsx file starting with "use client", imports from react only. Put the CSS in a template string rendered as <style href="ui-dither-cursor" precedence="ui">, with every class prefixed dc-. The root fills its parent (position relative, width and height 100%, overflow hidden, isolation isolate), paints #f9f9f9 and sets touch-action: none. Props with defaults: ditherSize 4, radius 0.12, exponent 2, decay 0.022, momentum 0.9, color "#ef3b2d" (hex, the accent). Layers, back to front: 1. A canvas (aria-hidden) at dither-pixel resolution, ceil(root size / ditherSize), scaled back up in CSS with image-rendering: pixelated. Size it with a ResizeObserver on the root; reallocate the fields when the grid changes. 2. A hairline grid: 111px cells, 1px #ececec lines, a 2px #dadada dot per cell, masked out behind the copy. 3. Centred copy: "Every move you make", a line break, then "leaves a trail" in the accent. Inter 500, clamp(24px, 7cqi, 60px) (the root is an inline-size container), line height 1.08, letter spacing -.02em, ink #262626. Under it a 13px hint in rgba(38,38,38,.56): "Move your cursor", or "Drag your finger" when (hover: none) or (pointer: coarse) matches. The accent text transitions over .9s with cubic-bezier(.3,.7,.2,1) when color changes. Simulation, a fluid with no pressure solve: - Grid: one cell per 2x2 dither pixels, ceil(columns / 2) + 1 wide, likewise tall. Fields D, U, V plus swap buffers (Float32Array). - Pointer in cells, relative to the root's bounding rect. Blob radius R in px = clamp(radius x height, min(80, 0.15 x width), 180). - Smoothed velocity: v += (delta / frames - v) x 0.5, where frames = clamp(elapsed ms / 16.7, 0.5, 2). Cap speed at 2.6 cells per frame, then multiply by momentum. - Splat along the segment from the last point in steps of R / 4, each with amount 0.55 x max(0.35, step length / (R / 4)). Density inside R gains amount x min(1, (1 - r / R) x 1.7) ^ exponent, capped at 1.8. Velocity: inside a disc of radius 1.6R centred 0.5R ahead along the motion, blend U and V toward the splat velocity by min(1, (1 - r / 1.6R) x 1.6) x 0.7. - Each frame (dt in 60fps frames, at most 3): for every cell, step back by (U, V) x dt and sample D, U and V there bilinearly, reading zero outside the grid. New density is that minus decay x dt, floored at 0. New velocity is that times 0.95 ^ dt. Swap buffers. - Draw: each dither pixel samples D at its centre, takes min(0.3, d) and shows the accent where that beats its 8x8 Bayer threshold, (value + 0.5) / 64; otherwise transparent. Write through a Uint32Array view of an ImageData and putImageData. - Read the accent from the accent text's computed color, cached for 30ms, so the trail cross-fades with the text. - Stop requestAnimationFrame when no density is left (zero the velocity), off screen (IntersectionObserver) or in a hidden tab. Restart on the next input. Input: pointer events on the root. Mouse and pen paint on move. Touch and pen start a fresh stroke on pointerdown; pointerup, pointercancel and pointerleave end it. Under prefers-reduced-motion, attach nothing, leave the canvas empty and hide the hint. Remove all listeners and observers on unmount.
"use client";
/*
* Dither cursor: the background effect from Alert's home page (alert-bice.vercel.app). A blob of
* ordered-dither pixels follows the pointer and carries its momentum: stop moving and it keeps sliding,
* stretching into a comet, while it thins out through the Bayer pattern and fades. Here it runs behind a
* short headline whose second line is in the accent `color`.
*
* How it works: a tiny fluid with no pressure solve, a density field and a velocity field on a coarse grid
* (one cell per 2x2 dither pixels). The pointer splats density and its own velocity into them; each frame
* both are carried along by the velocity (semi-Lagrangian advection), velocity bleeds off with friction
* and density with `decay`. A finer grid of dither pixels samples the density against an 8x8 Bayer matrix,
* written straight into ImageData at that resolution and scaled up with `image-rendering: pixelated`.
* The loop sleeps once everything has faded, and while the component is off screen or the tab is hidden.
*
* Mouse and pen paint on hover; touch paints while you drag (the root sets `touch-action: none`, so a
* drag that starts on it paints instead of scrolling the page). With reduced motion there's no trail.
*
* Usage (it fills its parent, so give the parent a size):
* import DitherCursor from "./DitherCursor";
* <div style={{ height: 460 }}><DitherCursor /></div>
* <DitherCursor ditherSize={3} decay={0.03} color="#0b6e4f" />
*
* Requirements: React 19 (the <style href precedence> tag is hoisted into <head> once, however many copies
* are mounted). No other dependencies. Colors are hex. The headline uses the --font-inter CSS variable if
* your page defines it, then Inter by name, then system fonts.
*/
import { useEffect, useRef, type CSSProperties } from "react";
type Props = {
/** Size of one dither pixel, in CSS px. */
ditherSize?: number;
/** Blob radius, as a fraction of the component's height (clamped to a sane px range). */
radius?: number;
/** Edge falloff. Higher is a softer, wider dithered rim around the solid core. */
exponent?: number;
/** How much the blob fades per frame (at 60fps). */
decay?: number;
/** How much of the pointer's speed the blob keeps, so it slides on after the pointer stops. */
momentum?: number;
/** The accent: the trail and the headline's second line. Hex. */
color?: string;
};
// 8x8 Bayer matrix, as thresholds in (0, 1).
const BAYER = [
0, 32, 8, 40, 2, 34, 10, 42, 48, 16, 56, 24, 50, 18, 58, 26, 12, 44, 4, 36, 14, 46, 6, 38, 60, 28, 52, 20, 62, 30, 54, 22,
3, 35, 11, 43, 1, 33, 9, 41, 51, 19, 59, 27, 49, 17, 57, 25, 15, 47, 7, 39, 13, 45, 5, 37, 63, 31, 55, 23, 61, 29, 53, 21,
].map((v) => (v + 0.5) / 64);
const SIM = 2; // the flow runs on a grid this many dither pixels per cell; the dither samples it bilinearly
const PEAK = 0.3; // most density shown: even the core stays a sparse halftone, full color but mostly gaps, so content reads through it
const FILL = 0.55; // density one pass of the pointer lays down; passes add up, so the head stays solid
const CAP = 1.8; // density can bank above PEAK so a well-fed head outlasts a one-pass tail
const FRICTION = 0.95; // velocity kept per frame
const MAX_V = 2.6; // sim cells per frame
const FLOW = 1.6; // velocity splat radius, relative to the blob
const LEAD = 0.5; // how far ahead of the pointer the velocity splat sits, relative to the blob
const CORE = 1.7; // how far the solid core reaches before the dithered rim starts (higher = bigger core)
let colorKey = "", colorVal = 0;
/** A hex color, or the rgb() a transitioning color computes to, as little-endian RGBA. */
function packed(c: string) {
if (c === colorKey) return colorVal;
let r = 0, g = 0, b = 0;
const m = c.match(/rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)/);
if (m) [r, g, b] = [m[1], m[2], m[3]].map((n) => Math.round(+n));
else {
let h = c.replace("#", "");
if (h.length === 3) h = h.replace(/./g, "$&$&");
const n = parseInt(h.slice(0, 6), 16) || 0;
r = n >> 16; g = (n >> 8) & 255; b = n & 255;
}
colorKey = c;
colorVal = ((255 << 24) | (b << 16) | (g << 8) | r) >>> 0;
return colorVal;
}
const css = `
.dc{--dc-bg:#f9f9f9;--dc-ink:#262626;--dc-muted:rgba(38,38,38,.56);--dc-line:#ececec;--dc-ease:cubic-bezier(.3,.7,.2,1);container:dc/inline-size;position:relative;width:100%;height:100%;overflow:hidden;isolation:isolate;background:var(--dc-bg);color:var(--dc-ink);font-family:var(--font-inter,Inter),system-ui,sans-serif;-webkit-font-smoothing:antialiased;touch-action:none;-webkit-tap-highlight-color:transparent}
.dc *,.dc *::before,.dc *::after{box-sizing:border-box}
.dc ::selection{background:color-mix(in srgb,var(--dc-accent) 20%,#f9f9f9);color:var(--dc-accent)}
.dc-canvas{position:absolute;left:0;top:0;z-index:0;display:block;image-rendering:pixelated;pointer-events:none}
/* Alert's hairline grid with a dot in each cell, drawn over the trail, faded out behind the copy */
.dc-grid{position:absolute;inset:0;z-index:1;pointer-events:none;background-image:radial-gradient(circle,#dadada 0 1px,transparent 1.5px),linear-gradient(to right,var(--dc-line) 1px,transparent 1px),linear-gradient(to bottom,var(--dc-line) 1px,transparent 1px);background-size:111px 111px;background-position:center;-webkit-mask-image:radial-gradient(closest-side at 50% 45%,transparent 50%,#000 100%);mask-image:radial-gradient(closest-side at 50% 45%,transparent 50%,#000 100%)}
.dc-copy{position:absolute;inset:0;z-index:2;display:flex;flex-direction:column;align-items:center;justify-content:center;padding:24px;text-align:center;pointer-events:none;user-select:none;-webkit-user-select:none}
.dc-h{margin:0;font-size:clamp(24px,7cqi,60px);line-height:1.08;font-weight:500;letter-spacing:-.02em;color:var(--dc-ink);text-wrap:balance}
.dc-hot{color:var(--dc-accent);transition:color .9s var(--dc-ease)}
.dc-hint{margin:18px 0 0;font-size:13px;line-height:1.4;color:var(--dc-muted)}
.dc-touch{display:none}
@media (hover:none),(pointer:coarse){.dc-mouse{display:none}.dc-touch{display:inline}}
@media (prefers-reduced-motion:reduce){
.dc-hint{display:none}
.dc *,.dc *::before,.dc *::after{transition:none!important}
}
`;
export default function DitherCursor({ ditherSize = 4, radius = 0.12, exponent = 2, decay = 0.022, momentum = 0.9, color: accent = "#ef3b2d" }: Props) {
const rootRef = useRef<HTMLDivElement>(null);
const canvasRef = useRef<HTMLCanvasElement>(null);
const hotRef = useRef<HTMLSpanElement>(null);
const opts = useRef({ radius, exponent, decay, momentum, accent });
useEffect(() => { opts.current = { radius, exponent, decay, momentum, accent }; });
useEffect(() => {
const root = rootRef.current;
const canvas = canvasRef.current;
const ctx = canvas?.getContext("2d");
if (!root || !canvas || !ctx) return;
if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
const ds = Math.max(1, Math.round(ditherSize));
const cell = ds * SIM; // sim cell, CSS px
let W = 0, H = 0, gw = 0, gh = 0, sw = 0, sh = 0;
let D = new Float32Array(0), U = D, V = D, D2 = D, U2 = D, V2 = D;
let img = ctx.createImageData(1, 1), px = new Uint32Array(img.data.buffer);
let raf = 0, last = 0, live = false, onScreen = true, tabShown = !document.hidden;
let has = false, mx = 0, my = 0, mt = 0, vx = 0, vy = 0; // pointer, in sim cells, and its smoothed velocity
let colAt = 0, col = "";
const size = () => {
W = root.clientWidth; H = root.clientHeight;
const nw = Math.max(1, Math.ceil(W / ds)), nh = Math.max(1, Math.ceil(H / ds));
if (nw === gw && nh === gh) return;
gw = nw; gh = nh;
sw = Math.ceil(gw / SIM) + 1; sh = Math.ceil(gh / SIM) + 1;
canvas.width = gw; canvas.height = gh;
canvas.style.width = `${gw * ds}px`; canvas.style.height = `${gh * ds}px`;
const n = sw * sh;
D = new Float32Array(n); U = new Float32Array(n); V = new Float32Array(n);
D2 = new Float32Array(n); U2 = new Float32Array(n); V2 = new Float32Array(n);
img = ctx.createImageData(gw, gh);
px = new Uint32Array(img.data.buffer);
};
// The accent as it paints right now: read off the headline's accent words, whose color transitions,
// so the trail cross-fades with the text. Cached briefly because it's asked once per frame.
const color = () => {
const now = performance.now();
if (!col || now - colAt > 30) {
colAt = now;
col = (hotRef.current && getComputedStyle(hotRef.current).color) || opts.current.accent;
}
return col;
};
// Bilinear read of a sim field; zero outside the grid so the blob can slide off the edge.
const at = (f: Float32Array, x: number, y: number) => {
const x0 = Math.floor(x), y0 = Math.floor(y), fx = x - x0, fy = y - y0;
const inX0 = x0 >= 0 && x0 < sw, inX1 = x0 + 1 >= 0 && x0 + 1 < sw;
const r0 = y0 >= 0 && y0 < sh ? y0 * sw : -1, r1 = y0 + 1 >= 0 && y0 + 1 < sh ? (y0 + 1) * sw : -1;
const a = r0 >= 0 && inX0 ? f[r0 + x0] : 0, b = r0 >= 0 && inX1 ? f[r0 + x0 + 1] : 0;
const c = r1 >= 0 && inX0 ? f[r1 + x0] : 0, d = r1 >= 0 && inX1 ? f[r1 + x0 + 1] : 0;
return (a + (b - a) * fx) * (1 - fy) + (c + (d - c) * fx) * fy;
};
// One round splat: a solid core that breaks into dither toward the rim, plus the pointer's
// velocity over a wider disc pushed ahead of it. The flow has to reach past the leading rim,
// or that edge sits in still air and the core just piles into it; and because the flow is
// strongest in front and weak behind, the head outruns the tail and the blob draws out into
// a comet when the pointer stops.
const splat = (cx: number, cy: number, R: number, svx: number, svy: number, amt: number) => {
const e = opts.current.exponent;
const sp = Math.hypot(svx, svy) || 1;
const vcx = cx + (svx / sp) * R * LEAD, vcy = cy + (svy / sp) * R * LEAD;
const Rv = R * FLOW, reach = R * LEAD + Rv;
const x0 = Math.max(0, Math.floor(cx - reach)), x1 = Math.min(sw - 1, Math.ceil(cx + reach));
const y0 = Math.max(0, Math.floor(cy - reach)), y1 = Math.min(sh - 1, Math.ceil(cy + reach));
for (let y = y0; y <= y1; y++) {
for (let x = x0; x <= x1; x++) {
const i = y * sw + x;
const rv = Math.hypot(x - vcx, y - vcy);
if (rv < Rv) {
const w = Math.min(1, (1 - rv / Rv) * 1.6) * 0.7; // flat through the head, fading behind
U[i] += (svx - U[i]) * w;
V[i] += (svy - V[i]) * w;
}
const r = Math.hypot(x - cx, y - cy);
if (r >= R) continue;
const s = Math.pow(Math.min(1, (1 - r / R) * CORE), e);
D[i] = Math.min(CAP, D[i] + amt * s);
}
}
};
const frame = (now: number) => {
const dt = last ? Math.min(3, (now - last) / (1000 / 60)) : 1;
last = now;
const fade = opts.current.decay * dt, keep = Math.pow(FRICTION, dt);
// Advect density and velocity along the velocity field.
live = false;
for (let y = 0; y < sh; y++) {
for (let x = 0; x < sw; x++) {
const i = y * sw + x;
const fx = x - U[i] * dt, fy = y - V[i] * dt;
const d = at(D, fx, fy) - fade;
D2[i] = d > 0 ? d : 0;
U2[i] = at(U, fx, fy) * keep;
V2[i] = at(V, fx, fy) * keep;
if (d > 0) live = true;
}
}
[D, D2] = [D2, D]; [U, U2] = [U2, U]; [V, V2] = [V2, V];
// Dither: each pixel samples the density and shows if it beats its Bayer threshold.
const on = packed(color());
for (let y = 0; y < gh; y++) {
const row = (y & 7) << 3, fy = (y + 0.5) / SIM - 0.5;
for (let x = 0; x < gw; x++) {
px[y * gw + x] = Math.min(PEAK, at(D, (x + 0.5) / SIM - 0.5, fy)) > BAYER[row | (x & 7)] ? on : 0;
}
}
ctx.putImageData(img, 0, 0);
if (live && onScreen && tabShown) raf = requestAnimationFrame(frame);
else {
raf = 0; last = 0;
if (!live) { U.fill(0); V.fill(0); }
}
};
const wake = () => { if (!raf && onScreen && tabShown) raf = requestAnimationFrame(frame); };
const sleep = () => { cancelAnimationFrame(raf); raf = 0; last = 0; };
const move = (e: PointerEvent) => {
if (!W || !H) return;
const rect = root.getBoundingClientRect();
const cx = (e.clientX - rect.left) / cell, cy = (e.clientY - rect.top) / cell;
const { radius: r, momentum: m } = opts.current;
// The site clamps the radius to 80-180px; the floor comes down in narrow frames so a phone isn't half blob.
const R = Math.min(180, Math.max(Math.min(80, W * 0.15), r * H)) / cell;
if (!has) { has = true; mx = cx; my = cy; mt = e.timeStamp; }
const dx = cx - mx, dy = cy - my;
// Clamped so a burst of sparse events still reads as a fast move rather than a crawl.
const frames = Math.min(2, Math.max(0.5, (e.timeStamp - mt) / (1000 / 60)));
// Smoothed pointer velocity in cells/frame, capped so a flick doesn't fling the blob away.
vx += (dx / frames - vx) * 0.5; vy += (dy / frames - vy) * 0.5;
const sp = Math.hypot(vx, vy), cap = sp > MAX_V ? MAX_V / sp : 1;
// Splat along the segment so fast moves leave a continuous body, not beads.
// Density per step scales with the distance covered, so ink per unit of path stays even;
// the floor keeps a slow drift from drawing nothing.
const step = R / 4, dist = Math.hypot(dx, dy);
const n = Math.max(1, Math.ceil(dist / step));
const amt = FILL * Math.max(0.35, dist / n / step);
for (let s = 1; s <= n; s++) splat(mx + (dx * s) / n, my + (dy * s) / n, R, vx * cap * m, vy * cap * m, amt);
mx = cx; my = cy; mt = e.timeStamp;
live = true;
wake();
};
const lift = () => { has = false; vx = vy = 0; };
// Touch and pen start a fresh stroke where they land; a mouse paints on hover alone.
const down = (e: PointerEvent) => { if (e.pointerType !== "mouse") { lift(); move(e); } };
const up = (e: PointerEvent) => { if (e.pointerType !== "mouse") lift(); };
const onVisibility = () => {
tabShown = !document.hidden;
if (!tabShown) sleep();
else if (live) wake();
};
size();
const ro = new ResizeObserver(size);
ro.observe(root);
const io = new IntersectionObserver(([en]) => {
onScreen = en.isIntersecting;
if (!onScreen) sleep();
else if (live) wake();
});
io.observe(root);
root.addEventListener("pointermove", move, { passive: true });
root.addEventListener("pointerdown", down, { passive: true });
root.addEventListener("pointerup", up);
root.addEventListener("pointercancel", lift);
root.addEventListener("pointerleave", lift);
document.addEventListener("visibilitychange", onVisibility);
return () => {
sleep();
ro.disconnect();
io.disconnect();
root.removeEventListener("pointermove", move);
root.removeEventListener("pointerdown", down);
root.removeEventListener("pointerup", up);
root.removeEventListener("pointercancel", lift);
root.removeEventListener("pointerleave", lift);
document.removeEventListener("visibilitychange", onVisibility);
};
}, [ditherSize]);
return (
<div className="dc" ref={rootRef} style={{ "--dc-accent": accent } as CSSProperties}>
<style href="ui-dither-cursor" precedence="ui">{css}</style>
<canvas ref={canvasRef} className="dc-canvas" aria-hidden="true" />
<div className="dc-grid" aria-hidden="true" />
<div className="dc-copy">
<p className="dc-h">Every move you make<br /><span className="dc-hot" ref={hotRef}>leaves a trail</span></p>
<p className="dc-hint"><span className="dc-mouse">Move your cursor</span><span className="dc-touch">Drag your finger</span></p>
</div>
</div>
);
}






