Specification
- Catalogue
- No. 106 of 110
- Section
- Loading and progress
- Interaction
- Loading
- Element
- Media, Loader
- Preview
- Live component
- Imports
- react 19.3.1
- Added
Notes
A grid of grey squares churns while a picture is made, then each square takes the picture's colour and the picture itself fades in.
A wait for a generated or uploaded image gets a shape that is already the picture's shape, and the picture arrives out of it instead of popping in.
Twelve by twelve cells on a 2D canvas, each set from a few slow waves, a ridge that sweeps across and a flicker that steps ten times a second, quantised to five grey levels. On the entry page Generate churns for 2.2s, then the cells turn to the picture's own colours one by one over 0.9s, then the picture fades in out of a 6px blur over 0.45s. On a card the mosaic churns while hovered. Under reduced motion the picture appears at once.
Changed from the library: a 2D canvas instead of a shader, one preset, grey cells in the site's text colour.
The picture in the demo is sample content; a real build uses the client's own.
Code
React and plain CSS"use client";
import { useEffect, useRef, useState } from "react";
import type { LivePreviewProps } from "@/components/live/types";
import { useReducedMotion } from "@/lib/client/hooks";
import styles from "./pixel-mosaic.module.css";
const GRID = 12;
const SIZE = 144;
const CELL = SIZE / GRID;
const IMAGE = { src: "/samples/studio-flowers.svg", alt: "A pale vase holding a few dried stems, a sample illustration" };
/** Entry page timings: churn, then each cell takes the picture's colour, then the picture itself fades in. */
const CHURN_MS = 2200;
const RESOLVE_MS = 900;
/** The frame a resting mosaic shows. */
const REST_TIME = 3.1;
type Rgb = [number, number, number];
/** A stable pseudo-random number per cell and step. */
const hash = (x: number, y: number, s: number) => {
const n = Math.sin(x * 127.1 + y * 311.7 + s * 74.7) * 43758.5453;
return n - Math.floor(n);
};
/**
* Brightness of one cell at time t: a few slow waves for the churn, a ridge
* that sweeps across like a shape being found, and a per-cell flicker that
* steps ten times a second. Quantised to a handful of grey levels.
*/
function level(x: number, y: number, t: number): number {
const waves =
Math.sin(x * 0.8 + t * 1.2) * Math.cos(y * 0.65 - t * 0.85) +
Math.sin((x + y) * 0.45 + t * 0.7) * 0.8 +
Math.sin(x * 1.6 - y * 1.2 + t * 1.9) * 0.45;
const ridge = Math.max(0, 1 - Math.abs(x - y * 0.9 - ((t * 2.2) % 18) + 3) / 1.4);
const flicker = hash(x, y, Math.floor(t * 10)) - 0.5;
const v = 0.34 + waves * 0.2 + ridge * 0.42 + flicker * 0.34;
const steps = [0.04, 0.1, 0.18, 0.28, 0.42];
return steps[Math.max(0, Math.min(steps.length - 1, Math.floor(v * steps.length)))] ?? 0.04;
}
/** Picture colours, one per cell, read once from the sample at mosaic resolution. */
function useCellColours(enabled: boolean) {
const [colours, setColours] = useState<Rgb[] | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!enabled) return;
const img = new Image();
img.onload = () => {
const canvas = document.createElement("canvas");
canvas.width = GRID;
canvas.height = GRID;
const ctx = canvas.getContext("2d");
if (!ctx) {
setError("This browser cannot read the picture.");
return;
}
ctx.drawImage(img, 0, 0, GRID, GRID);
const data = ctx.getImageData(0, 0, GRID, GRID).data;
const out: Rgb[] = [];
for (let i = 0; i < GRID * GRID; i++) out.push([data[i * 4] ?? 0, data[i * 4 + 1] ?? 0, data[i * 4 + 2] ?? 0]);
setColours(out);
};
img.onerror = () => setError("The sample picture did not load.");
img.src = IMAGE.src;
}, [enabled]);
return { colours, error };
}
type Reveal = { colours: Rgb[]; startedAt: number } | null;
function drawMosaic(ctx: CanvasRenderingContext2D, t: number, ink: string, pixelRatio: number, reveal: Reveal, now: number) {
ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);
ctx.clearRect(0, 0, SIZE, SIZE);
const progress = reveal ? Math.min(1, (now - reveal.startedAt) / RESOLVE_MS) : 0;
for (let y = 0; y < GRID; y++) {
for (let x = 0; x < GRID; x++) {
const i = y * GRID + x;
const colour = reveal?.colours[i];
// Each cell turns at its own moment, so the picture arrives scattered rather than as a wipe.
if (colour && hash(x, y, 1) < progress) {
ctx.globalAlpha = 1;
ctx.fillStyle = `rgb(${colour[0]} ${colour[1]} ${colour[2]})`;
} else {
ctx.globalAlpha = level(x, y, t);
ctx.fillStyle = ink;
}
ctx.fillRect(x * CELL + 0.5, y * CELL + 0.5, CELL - 1, CELL - 1);
}
}
ctx.globalAlpha = 1;
}
type Phase = "idle" | "churn" | "resolve" | "done";
export default function PixelMosaic({ active, context }: LivePreviewProps) {
const canvasRef = useRef<HTMLCanvasElement>(null);
const reduce = useReducedMotion();
const detail = context === "detail";
const [phase, setPhase] = useState<Phase>("idle");
const { colours, error } = useCellColours(detail);
const playing = !reduce && (detail ? phase === "churn" || phase === "resolve" : active);
const clock = useRef(REST_TIME);
const revealRef = useRef<Reveal>(null);
// Entry page: churn for a moment, then resolve into the picture.
useEffect(() => {
if (phase === "churn") {
const id = window.setTimeout(() => setPhase(colours ? "resolve" : "done"), reduce ? 0 : CHURN_MS);
return () => window.clearTimeout(id);
}
if (phase === "resolve" && colours) {
revealRef.current = { colours, startedAt: performance.now() };
const id = window.setTimeout(() => setPhase("done"), reduce ? 0 : RESOLVE_MS);
return () => window.clearTimeout(id);
}
if (phase === "idle") revealRef.current = null;
}, [phase, colours, reduce]);
useEffect(() => {
const canvas = canvasRef.current;
if (!canvas) return;
const ctx = canvas.getContext("2d");
if (!ctx) throw new Error("Pixel mosaic: the 2D canvas is not available.");
const pixelRatio = Math.min(4, (window.devicePixelRatio || 1) * 2);
canvas.width = SIZE * pixelRatio;
canvas.height = SIZE * pixelRatio;
const ink = () => getComputedStyle(canvas).color;
let frame = 0;
let last = performance.now();
const tick = (now: number) => {
clock.current += Math.min(0.05, (now - last) / 1000);
last = now;
drawMosaic(ctx, clock.current, ink(), pixelRatio, revealRef.current, now);
frame = requestAnimationFrame(tick);
};
const still = () => drawMosaic(ctx, clock.current, ink(), pixelRatio, revealRef.current, performance.now());
if (playing) frame = requestAnimationFrame(tick);
else still();
const themeObserver = new MutationObserver(still);
themeObserver.observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme"] });
const scheme = window.matchMedia("(prefers-color-scheme: dark)");
scheme.addEventListener("change", still);
return () => {
cancelAnimationFrame(frame);
themeObserver.disconnect();
scheme.removeEventListener("change", still);
};
}, [playing]);
const label = phase === "churn" || phase === "resolve" ? "Generating" : phase === "done" ? "Generate again" : "Generate";
return (
<div className={styles.root}>
<div className={styles.frame}>
<canvas ref={canvasRef} className={styles.canvas} width={SIZE} height={SIZE} role="img" aria-label="A mosaic of grey squares, working" />
{detail && (
<img className={styles.picture} src={IMAGE.src} alt={phase === "done" ? IMAGE.alt : ""} data-shown={phase === "done" || undefined} width={SIZE} height={SIZE} />
)}
</div>
{detail && (
<div className={styles.bar}>
<button
type="button"
className={styles.button}
aria-disabled={phase === "churn" || phase === "resolve" || undefined}
onClick={() => {
if (phase === "churn" || phase === "resolve") return;
revealRef.current = null;
setPhase("churn");
}}
>
{label}
</button>
{error && (
<p className={styles.error} role="alert">
{error}
</p>
)}
</div>
)}
</div>
);
}