Skip to content
Browse documentation

A generated image gathers from grains of its own colours, centre first, and locks sharp. Sand away, in reverse.

Used forImage generatorsAI avatarsUpscalersGalleries

Install with the shadcn CLI

$ npx shadcn@latest add https://hairlineui.com/r/grain-reveal.json

Registered the namespace? Then it’s shadcn add @hairline/grain-reveal. Set it up

Templates

Need the whole page?

61 Next.js landing pages, each designed from scratch. Try any of them live; one is $39, all of them $159, and 6 are free.

All 61 templates

Where it’s used

  • Image generators

    The result of a prompt assembling in place.

  • AI avatars

    A generated portrait gathering into its frame.

  • Upscalers

    The upscaled image arriving over the old one.

  • Galleries

    New generations landing in a grid, paired with Sand away for deletes.

What it handles for you

Generated images usually pop in, or fade in from a grey box, which says nothing about the work behind them.

Instead of wiring uploading spinnerfade-in imageparticle animation librarycanvas particle effect
  1. Grains of the real picture

    Each grain carries a real pixel colour, so the gather is the image itself arriving.

  2. Nothing before pixels

    While it waits the grains are neutral; colour only appears once the image exists.

  3. Centre first

    The middle locks in first and the edges follow, so the subject is readable early.

  4. Pairs with Sand away

    The same engine runs both ways: gather here, blow away there.

  5. Safe without CORS

    If the image can’t be read, it sharpens out of a blur instead of failing.

  6. Sleeps off screen

    The waiting grains only draw while the frame is on screen.

Overview

A reveal that is honest about where the picture comes from. While your generation runs, a few neutral grains drift in the frame: no colours, because there are no pixels yet. When the image is ready and loaded, it is cut into grains of its real colours that swirl in from around their places, the centre first and the edges after, and lock into the sharp picture over 1.5s. It is Sand away played backwards, so the two make a pair: what you generate gathers, what you delete blows away. Reading the colours needs an image served with CORS; without it, the picture simply sharpens out of a blur.

States

waiting
150 neutral grains in the text colour drift slowly at 12–28% opacity, drawn only while the frame is on screen.
gathering
Up to 7,000 grains of the image’s colours swirl in from 18–62px around their places, centre first, over 1.5s; the last 20% crossfades into the sharp picture.
shown
The plain image. onReady fires.
without CORS
The image sharpens from blur(12px) over 0.9s instead of gathering.
failed
The well with “This image couldn’t be created.” and Try again when onRetry is passed.

Usage

usage.tsx
import { GrainReveal } from "@/components/grain-reveal";<GrainReveal  src={image?.url}  status={job.status}  crossOrigin="anonymous"  alt={prompt}  onRetry={regenerate}  className="aspect-square w-80"/>

Works with

Polling your generation API

Start a generation, poll its status, and hand the component the real state. Any API that reports generating, ready and failed works the same way.

example.tsx
"use client";import * as React from "react";import { GrainReveal } from "@/components/grain-reveal";type Job = { id: string; status: "generating" | "ready" | "error"; url?: string; progress?: number };export function Generation({ prompt }: { prompt: string }) {  const [job, setJob] = React.useState<Job | null>(null);  async function generate() {    const { id } = await fetch("/api/generate", { method: "POST", body: JSON.stringify({ prompt }) }).then((r) => r.json());    setJob({ id, status: "generating" });    const poll = window.setInterval(async () => {      const next: Job = await fetch(`/api/generate/${id}`).then((r) => r.json());      setJob(next);      if (next.status !== "generating") window.clearInterval(poll);    }, 1000);  }  return (    <div className="grid gap-3">      <GrainReveal        src={job?.url}        status={job?.status ?? "generating"}  crossOrigin="anonymous"        alt={prompt}        onRetry={generate}        className="aspect-square w-80"      />      <button onClick={generate}>Generate</button>    </div>  );}

Props

src
string
The generated image. It can arrive before or with status "ready"; the reveal waits until it has loaded and decoded.
status
"generating" | "ready" | "error"
Your generation’s real state. Nothing plays on a timer.
progress
number
0 to 1, if your API reports it. Shown as a small rolling figure; without it, no number is shown.
alt
string
The image’s text alternative, usually its prompt.
crossOrigin
"anonymous" | "use-credentials"
Set it when your image host sends CORS headers.
onReady
() => void
Called once the reveal has played, or the image is shown without one.
onRetry
() => void
Shows Try again when the generation fails.
labels
{ generating?, ready?, failed?, retry? }
Words for the progress tag, the announcements and the failure.
className
string
Size the frame here, e.g. "aspect-square w-72".

Accessibility and motion

  • It follows your status: it waits while "generating", and plays only once status is "ready" and the image has loaded and decoded (img.decode), so it can never finish before the picture does. An image that was already there when the page loaded is simply shown.
  • The figure has aria-busy while it waits, and a status line announces Generating, Image ready or the failure; the image keeps its alt text.
  • The gather draws on one canvas only while it plays, and is removed when the image is shown.
  • Serve your images with CORS and pass crossOrigin="anonymous" for the grains; setting crossOrigin on a host without CORS headers makes the image fail to load, so leave it off there.
  • Under reduced motion the image appears in place, with no drift while waiting.

Requirements

React 19, Tailwind CSS v4 and shadcn/ui theme variables (any style, light and dark). Icons from lucide-react.

The CLI also installs Number roll.

Source

"use client";/* ───────────────────────────────────────────────────────── * GRAIN REVEAL: the picture gathers from its own grains * * While your generation runs, a few neutral grains drift in the * well: no colours yet, because there are no pixels yet. When * the image is ready and loaded, it is cut into grains of its * real colours that swirl in from around their places, centre * first, and lock into the sharp picture. Sand away in reverse. * * Reading the colours needs a CORS-clean image (crossOrigin); * without it the picture sharpens out of a blur instead. * ───────────────────────────────────────────────────────── */import * as React from "react";import { clamp01, makeGrains, move, snapshot, type Grain, type Snapshot } from "./image-grains";import { Announce, ErrorFace, ProgressTag, frameClass, useArrival, useNextFrame, useReducedMotion, type RevealProps } from "./image-arrival";export type { GenerationStatus, RevealLabels } from "./image-arrival";export type GrainRevealProps = RevealProps;const GATHER = 1500;const DOTS = 150;function drawGather(ctx: CanvasRenderingContext2D, shot: Snapshot, grains: Grain[], t: number) {  ctx.clearRect(0, 0, shot.w, shot.h);  const cw = shot.w / shot.cols;  for (let i = 0; i < grains.length; i++) {    const g = grains[i];    // Every grain is home by t = 0.88, before the crossfade, so no seams show between them.    const life = clamp01((t - g.release * 0.75) / 0.44);    const m = move("gather", life, g.nx, g.ny, g.a, g.b);    const s = Math.max(1.2, cw * 1.04 * m.scale);    ctx.globalAlpha = m.alpha * (life > 0 ? 1 : 0.35);    ctx.fillStyle = g.colours[0];    ctx.fillRect(g.x + m.dx - s / 2, g.y + m.dy - s / 2, s, s);  }  // The last fifth crossfades into the sharp picture, so the grain grid never shows at rest.  if (t > 0.8 && shot.sharp) {    ctx.globalAlpha = clamp01((t - 0.8) / 0.2);    ctx.drawImage(shot.sharp, 0, 0, shot.w, shot.h);  }  ctx.globalAlpha = 1;}export function GrainReveal({ src, status, progress, alt, crossOrigin, onReady, onRetry, labels, className }: GrainRevealProps) {  const reduced = useReducedMotion();  const { phase, onLoad, onError, imageRef, finish } = useArrival(src, status, onReady);  const figure = React.useRef<HTMLElement>(null);  const canvas = React.useRef<HTMLCanvasElement>(null);  const [plain, setPlain] = React.useState(false);  if (phase === "waiting" && plain) setPlain(false);  const revealing = phase === "revealing";  const fadeIn = useNextFrame(revealing && plain);  // Waiting: a few neutral grains drift, only while the figure is on screen.  React.useEffect(() => {    if (phase !== "waiting") return;    const el = canvas.current;    const box = figure.current;    if (!el || !box) return;    const dpr = Math.min(window.devicePixelRatio || 1, 2);    const w = box.clientWidth;    const h = box.clientHeight;    el.width = Math.round(w * dpr);    el.height = Math.round(h * dpr);    const ctx = el.getContext("2d");    if (!ctx) return;    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);    const ink = getComputedStyle(box).color;    const dots = Array.from({ length: DOTS }, (_, i) => ({ x: ((i * 97) % 101) / 101, y: ((i * 61) % 103) / 103, a: (i * 0.618) % 1, s: 1.4 + ((i * 7) % 5) * 0.35 }));    let frame = 0;    let visible = true;    const draw = (now: number) => {      ctx.clearRect(0, 0, w, h);      ctx.fillStyle = ink;      for (const d of dots) {        const t = now / 1000;        const x = (d.x + Math.sin(t * 0.35 + d.a * 6.28) * 0.025) * w;        const y = (d.y + Math.cos(t * 0.29 + d.a * 9.1) * 0.025) * h;        ctx.globalAlpha = 0.12 + 0.16 * (0.5 + 0.5 * Math.sin(t * 0.9 + d.a * 12));        ctx.fillRect(x, y, d.s, d.s);      }      ctx.globalAlpha = 1;      if (visible && !reduced) frame = requestAnimationFrame(draw);    };    const io = new IntersectionObserver(([entry]) => {      visible = entry.isIntersecting;      cancelAnimationFrame(frame);      if (visible) frame = requestAnimationFrame(draw);    });    io.observe(box);    frame = requestAnimationFrame(draw);    return () => {      io.disconnect();      cancelAnimationFrame(frame);    };  }, [phase, reduced]);  // Ready: gather the real grains, or sharpen out of a blur when the pixels can't be read.  React.useEffect(() => {    if (!revealing) return;    const el = canvas.current;    const box = figure.current;    if (reduced || !el || !box) {      const id = window.setTimeout(finish, 0);      return () => window.clearTimeout(id);    }    const shot = snapshot(box);    if (!shot.cells) {      const id = window.setTimeout(() => setPlain(true), 0);      const done = window.setTimeout(finish, 900);      return () => {        window.clearTimeout(id);        window.clearTimeout(done);      };    }    const grains = makeGrains(shot, "gather");    const dpr = Math.min(window.devicePixelRatio || 1, 2);    el.width = Math.round(shot.w * dpr);    el.height = Math.round(shot.h * dpr);    const ctx = el.getContext("2d");    if (!ctx) return;    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);    let frame = 0;    const start = performance.now();    const step = (now: number) => {      const t = clamp01((now - start) / GATHER);      drawGather(ctx, shot, grains, t);      if (t < 1) frame = requestAnimationFrame(step);      else finish();    };    frame = requestAnimationFrame(step);    return () => cancelAnimationFrame(frame);  }, [revealing, reduced, finish]);  const shown = phase === "shown" || (revealing && plain && fadeIn);  return (    <figure ref={figure} className={frameClass(`text-muted-foreground ${className ?? ""}`)} aria-busy={phase === "waiting"}>      {src && (        // eslint-disable-next-line @next/next/no-img-element        <img          ref={imageRef}          key={src}          src={src}          alt={alt}          crossOrigin={crossOrigin}          onLoad={onLoad}          onError={onError}          draggable={false}          className="absolute inset-0 size-full object-cover"          style={{            opacity: shown ? 1 : 0,            filter: plain && revealing && !fadeIn ? "blur(12px)" : "blur(0px)",            transition: plain && revealing ? "opacity 600ms ease-out, filter 900ms cubic-bezier(0.16,1,0.3,1)" : "none",          }}        />      )}      {(phase === "waiting" || (revealing && !plain)) && <canvas ref={canvas} aria-hidden="true" className="pointer-events-none absolute inset-0 size-full" />}      {phase === "waiting" && <ProgressTag progress={progress} label={labels?.generating ?? "Generating"} />}      {phase === "error" && <ErrorFace labels={labels} onRetry={onRetry} />}      <Announce phase={phase} labels={labels} />    </figure>  );}

Registry item: /r/grain-reveal.json