Impeccable

Loupe Grid

A faint grid background whose marks swell, brighten and glow under your pointer. Use it behind a hero or sign-up section with one short headline.

BackgroundNo extra packagesLight + darkMobile
npx shadcn@latest add https://impeccableui.vercel.app/r/loupe-grid.json
Move your pointer over the grid, then switch the type with the pills. On a phone, touch and drag.

Run it in a project set up with shadcn. No other packages needed. Or open and copy the file into components/ui/loupe-grid.tsx.

Types

Four types. Plus and Dots are marks on their own. Plus and lines and Dots and lines join the same marks with faint lines, and the lines bend with the marks under the pointer.

Plus · type="plus"
Plus and lines · type="plus-lines"
Dots · type="dots"
Dots and lines · type="dots-lines"
<LoupeGrid type="plus" />        // plus marks (the default)
<LoupeGrid type="plus-lines" />  // plus marks on a grid of lines
<LoupeGrid type="dots" />        // dots
<LoupeGrid type="dots-lines" />  // dots on a grid of lines

Prompts

Paste one into Claude Code, Cursor or any AI coding tool. Install adds this exact background and asks only which section it goes behind. Blend asks three short questions (where, the type and spacing, and the colors), then fits it to your brand without changing how it reacts.

# Loupe Grid

A 1-file React component from Impeccable. Add it to this project so it works and looks exactly like the source below, in the one place I choose, and change nothing else.

A faint grid background whose marks swell, brighten and glow under the pointer, as if a loupe passed over it. On the types with lines, the lines bend with the marks. It sits behind the content and never catches a click.

## Before you build: one question

Look through this project first: its landing and hero sections, its sign-up and pricing sections, its root layout and which sections have plain, empty backgrounds. Then ask me this in one message and wait for my answer:

- **Where should it go?** Suggest the 1–3 sections it fits best behind (for example the hero, or the sign-up section), or the whole page. For a section, keep its content and wrap it in the grid. For the whole page, it goes once in the root layout, fixed to the screen. I can pick one or name another.
  *Why: the grid is quiet until the pointer passes over it, so it suits a calm section with a short headline and room around it, not a busy one full of cards and images.*

Ask nothing else. If I say *skip*, use the best suggestion.

## Keep it as it is

The faint grid of plus marks, the loupe that makes the nearby marks swell, light up, glow and spread a little under the pointer, and its smooth ease in and out are the design. Keep them exactly as in the source, with the default `type` (`"plus"`). If something doesn't fit my project, tell me instead of changing it.

- Add only the component file and the one place I picked. If it wraps an existing section, keep that section's content, spacing and background color. Don't add packages, change other files, or restyle anything.
- Don't add the demo parts from the Impeccable website: the row of type pills (Plus, Plus and lines, Dots, Dots and lines), the four type cards and their labels.

## Fastest path

If this project has a `components.json` (shadcn), run `npx shadcn@latest add https://impeccableui.vercel.app/r/loupe-grid.json`.
If the command succeeds, only fix import paths to match this project and skip ahead. If it fails or there is no `components.json`, build it by hand as below.

## Build it

- Stack: React 18 or 19 with TypeScript. No other packages: the grid is drawn on one canvas and the rest is a few lines of CSS.
- JavaScript project? Name the file `loupe-grid.jsx` and remove the type annotations; nothing else changes.
- Create this file, in this project's usual place for components:
  - `components/ui/loupe-grid.tsx`
- Keep these exports and their names: `LoupeGrid`, `LoupeGridProps`, `LoupeGridType`.
- Keep `"use client"` at the top in Next.js App Router projects. In other setups it is harmless.
- Keep the tuning values at the top exactly as written: `PLUS_ARM`, `PLUS_W`, `DOT_R`, `LINE_W`, `MARK_A`, `LINE_A`, `LINE_HOT_A`, `PUSH`, `GLOW`, `GLOW_DARK`, `GLOW_R`, `IN_MS`, `OUT_MS`, `FOLLOW_MS`, `TOUCH_HOLD_MS`, `STEP`, `LEVELS`, `MAX_PIXELS` and the `CSS` block. They are the design.
- Keep the fallbacks: with `prefers-reduced-motion: reduce` the marks still light up and glow but don't grow or move. On touch screens the loupe shows where a finger touches and fades 450ms after it lifts. Off screen and at rest nothing runs. A very large box draws a little softer instead of running out of memory.
- Keep the grid out of the way: `pointer-events: none`, `user-select: none` and `aria-hidden` on its layer. It must never catch a click, a text selection or a screen reader.

## Use it

```tsx
"use client";
import { LoupeGrid } from "@/components/ui/loupe-grid";

// Behind one section: wrap its content and give it a size.
export function Hero() {
  return (
    <LoupeGrid className="flex min-h-[560px] flex-col items-center justify-center gap-6 px-6">
      <h1>Ship the calm version</h1>
      <a href="/signup">Get started</a>
    </LoupeGrid>
  );
}

// Behind the whole page: once in the root layout, empty, fixed to the screen.
<LoupeGrid className="fixed inset-0 -z-10" />
```

- It is a `<div>` and takes every div prop. `className` and `style` go on the box: give it a size (or let it fill its parent) and, if you want one, a background color. The grid has none.
- Everything inside it sits above the grid and works as normal. Keep the section's own tag and landmarks (`<section>`, `<main>`) inside it, or wrap the grid inside the section.
- For a whole page, keep it empty and fixed, so it stays one screen big however long the page is.

## How the loupe works

Read this before you touch anything, so you know what the code does and why it must stay as it is.

1. **The grid.** Marks sit on an even grid, `gap` (56px) apart, centred in the box so the edges match. At rest they are drawn at 30% of `color` (the text color by default), and on the types with lines, faint lines at 10% run edge to edge through them. It has no background of its own.
2. **The layer.** The box is `position: relative` with `isolation: isolate`. The canvas sits in a layer at `z-index: -1` inside it, so everything passed as children always paints above the grid, and the box's own background color paints below it. The layer has `pointer-events: none`, so clicks and selection go straight to the content.
3. **Sensing.** It listens to the pointer on the whole window, not on the grid, so it still reacts under headlines and buttons on top of it. When the pointer is inside the box, the loupe eases in over 200ms; when it leaves, it fades out over 550ms. Both follow a smooth S curve, so they start and end softly. The loupe trails the pointer by about 60ms, so it glides instead of jumping. On touch, the finger's position counts while it is down, and the loupe fades 450ms after it lifts.
4. **The loupe.** Every mark within `radius` (150px) is lit by a smooth curve: fully at the pointer, nothing at the rim, so there is never a hard ring. A lit mark grows up to `magnify` (1.8 times), mixes from its faint color into `hoverColor`, gets a soft round glow behind it (weaker for a dark hover color, so it never smudges a light page), and spreads a few pixels away from the pointer. Lines are cut into 6px pieces inside the loupe, so they bend with the marks and brighten toward the pointer.
5. **Drawing.** The whole grid is drawn once. After that, each frame only clears and redraws the square around the loupe (and the square it left), and the loop stops the moment the loupe has settled. It draws only once the box comes near the screen and ignores the pointer while it is away. All timing runs on elapsed time, so it feels the same on slow phones and fast screens. The canvas is at most 2x the screen's pixel ratio, and its colors are read from the page again when the theme changes, so it follows light and dark mode.

## Check

- It type-checks and the page renders with no console errors.
- At rest the grid is faint and still. Moving the mouse over it: the marks within about 150px swell (up to 1.8 times right under the pointer), turn bright and glow softly, and spread a little; the effect eases in fast and fades out slowly when the pointer leaves. Text on top can still be selected and every button and link on top still works.
- It looks right in light and dark mode (check both), and the marks switch with the theme.
- On a phone, touching the grid shows the loupe under the finger and it fades shortly after lifting; the page still scrolls normally, with no sideways scroll.
- With `prefers-reduced-motion: reduce`, the marks still light up and glow, but don't grow or move.
- Nothing else on the site looks or behaves differently.
- Finish with a short report: the files you added or changed, where it's placed, and every place where you had to do something differently from the source, and why.

## Source

The reference implementation. Copy it as-is, then apply only the changes listed above.

### `components/ui/loupe-grid.tsx`

```tsx
"use client";

/**
 * Loupe Grid, from Impeccable.
 *
 * A quiet grid background that comes alive under the pointer, like a jeweller's
 * loupe passing over it. The marks near the pointer swell, brighten into the hover
 * color, glow softly and spread apart a little, and the lines bend around them.
 * The pointer moves on; the marks settle back. Everything eases in and out.
 *
 * Four types: plus marks, plus marks on lines, dots, or dots on lines.
 *
 * It sits behind whatever you put inside it. It is never selectable, never
 * catches a click, and is hidden from screen readers. Phones get the loupe
 * wherever a finger touches.
 *
 * No packages. One canvas. Only the small square around the pointer is redrawn,
 * and only while something moves; at rest nothing runs at all. It waits until it
 * is near the screen before it draws, and ignores the pointer while off screen.
 */

import { useEffect, useRef, type HTMLAttributes, type ReactNode } from "react";

export type LoupeGridType = "plus" | "plus-lines" | "dots" | "dots-lines";

export type LoupeGridProps = Omit<HTMLAttributes<HTMLDivElement>, "color"> & {
  /** Which marks: "plus", "plus-lines", "dots" or "dots-lines". Lines join the marks into a grid. */
  type?: LoupeGridType;
  /** Distance between marks, in px. */
  gap?: number;
  /** How far the loupe reaches from the pointer, in px. */
  radius?: number;
  /** How big the mark right under the pointer grows (1.8 = 80% bigger). 1 turns the growing off. */
  magnify?: number;
  /** Color of the marks and lines at rest, drawn faint. Any CSS color, including var(--…). Default: the text color. */
  color?: string;
  /** Color the marks turn near the pointer, and their glow. Default: the text color. */
  hoverColor?: string;
  /** Your content. It sits above the grid and works as normal. */
  children?: ReactNode;
};

/* ---------- tuning (the design: keep as written) ---------- */

const PLUS_ARM = 4.5; // px: from the middle of a plus to the end of an arm
const PLUS_W = 1.2; // px: thickness of a plus
const DOT_R = 1.5; // px: radius of a dot
const LINE_W = 1; // px: thickness of a line
const MARK_A = 0.3; // how strong a mark is at rest (share of its color)
const LINE_A = 0.1; // how strong a line is at rest
const LINE_HOT_A = 0.4; // how strong a line gets right under the pointer
const PUSH = 0.28; // how far marks spread away from the pointer: the bulge of the loupe
const GLOW = 0.3; // glow strength under the pointer, for a light hover color
const GLOW_DARK = 0.12; // the same for a dark hover color, so it never smudges a light page
const GLOW_R = 10; // px: glow radius around one mark at normal size
const IN_MS = 200; // the loupe eases in over this long
const OUT_MS = 550; // and out over this long, gentler
const FOLLOW_MS = 60; // how closely it trails the pointer
const TOUCH_HOLD_MS = 450; // after a finger lifts, the loupe stays this long, then fades
const STEP = 6; // px: lines bend in pieces this long inside the loupe
const LEVELS = 10; // shades a bent line is drawn in
const MAX_PIXELS = 8_000_000; // canvas size budget; a very large box draws a little softer instead of running out of memory

const TYPES: LoupeGridType[] = ["plus", "plus-lines", "dots", "dots-lines"];

const CSS = `
:where(.ilg) { position: relative; isolation: isolate; }
.ilg-layer { position: absolute; inset: 0; z-index: -1; overflow: hidden; pointer-events: none; user-select: none; -webkit-user-select: none; -webkit-touch-callout: none; }
.ilg-layer canvas { position: absolute; left: 0; top: 0; width: 100%; height: 100%; display: block; pointer-events: none; }`;

/* ---------- small helpers ---------- */

const num = (v: unknown, fallback: number, min: number, max: number) =>
  typeof v === "number" && Number.isFinite(v) ? Math.min(max, Math.max(min, v)) : fallback;

type RGBA = [number, number, number, number];

/** Any CSS color as [r, g, b, a], worked out by painting it, so every color format works (rgb, oklch, color()...). */
let probe: CanvasRenderingContext2D | null = null;
function toRgba(color: string): RGBA {
  probe ??= document.createElement("canvas").getContext("2d", { willReadFrequently: true });
  if (!probe) return [128, 128, 128, 1];
  probe.clearRect(0, 0, 1, 1);
  probe.fillStyle = "#808080";
  probe.fillStyle = color;
  probe.fillRect(0, 0, 1, 1);
  const [r, g, b, a] = probe.getImageData(0, 0, 1, 1).data;
  return [r, g, b, a / 255];
}

const isLight = ([r, g, b]: RGBA) => {
  const lin = (c: number) => ((c /= 255) <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4);
  return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b) > 0.4;
};

const mix = (a: RGBA, b: RGBA, t: number, aAlpha: number, bAlpha: number) =>
  `rgb(${Math.round(a[0] + (b[0] - a[0]) * t)} ${Math.round(a[1] + (b[1] - a[1]) * t)} ${Math.round(a[2] + (b[2] - a[2]) * t)} / ${(
    aAlpha + (bAlpha - aAlpha) * t
  ).toFixed(3)})`;

type Box = { x0: number; y0: number; x1: number; y1: number };

/* ---------- the background ---------- */

export function LoupeGrid({
  type = "plus",
  gap = 56,
  radius = 150,
  magnify = 1.8,
  color,
  hoverColor,
  className,
  children,
  ...rest
}: LoupeGridProps) {
  const rootRef = useRef<HTMLDivElement>(null);
  const layerRef = useRef<HTMLDivElement>(null);
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const refresh = useRef<() => void>(() => {});

  // Props the running code reads without starting over.
  const opts = useRef({ type, gap, radius, magnify, color, hoverColor });
  opts.current = {
    type: TYPES.includes(type) ? type : "plus",
    gap: Math.round(num(gap, 56, 12, 400)),
    radius: num(radius, 150, 24, 1200),
    magnify: num(magnify, 1.8, 1, 4),
    color,
    hoverColor,
  };

  useEffect(() => {
    refresh.current();
  }, [type, gap, radius, magnify, color, hoverColor]);

  useEffect(() => {
    const root = rootRef.current, layer = layerRef.current, canvas = canvasRef.current;
    if (!root || !layer || !canvas) return;
    const ctx = canvas.getContext("2d");
    if (!ctx) return;

    const reduceMq = matchMedia("(prefers-reduced-motion: reduce)");
    let still = reduceMq.matches; // reduced motion: marks light up and glow, but don't grow or move

    // Size, grid and colors.
    let w = 0, h = 0, dpr = 1, ox = 0, oy = 0, nx = 0, ny = 0, G = 56, R = 150, MAG = 1.8;
    let kind: LoupeGridType = "plus";
    let base: RGBA = [128, 128, 128, 1], hot: RGBA = [128, 128, 128, 1], glowA = GLOW;
    let sprite: HTMLCanvasElement | null = null;

    // The loupe: where it is (box pixels), how far it has eased in (p, 0 to 1), how strong that makes it (s), and the box it last drew in.
    const L = { x: 0, y: 0, p: 0, s: 0 };
    let drawn: Box | null = null;
    // The pointer, in screen pixels.
    const P = { cx: 0, cy: 0, has: false };
    let raf = 0, last = 0, visible = false, ready = false, holdTimer = 0;

    const readColors = () => {
      const read = (v: string | undefined) => {
        layer.style.color = v ?? "";
        const c = toRgba(getComputedStyle(layer).color);
        layer.style.color = "";
        return c;
      };
      base = read(opts.current.color);
      hot = read(opts.current.hoverColor);
      glowA = isLight(hot) ? GLOW : GLOW_DARK;
      // One soft round glow, drawn once and stamped under each lit mark.
      sprite ??= document.createElement("canvas");
      sprite.width = sprite.height = 64;
      const s = sprite.getContext("2d");
      if (s) {
        const g = s.createRadialGradient(32, 32, 0, 32, 32, 32);
        g.addColorStop(0, `rgb(${hot[0]} ${hot[1]} ${hot[2]} / ${hot[3]})`);
        g.addColorStop(0.4, `rgb(${hot[0]} ${hot[1]} ${hot[2]} / ${hot[3] * 0.35})`);
        g.addColorStop(1, `rgb(${hot[0]} ${hot[1]} ${hot[2]} / 0)`);
        s.clearRect(0, 0, 64, 64);
        s.fillStyle = g;
        s.fillRect(0, 0, 64, 64);
      }
    };

    // The marks sit on a grid centred in the box; lines run edge to edge through them.
    const layout = () => {
      const o = opts.current;
      kind = o.type;
      G = o.gap;
      R = o.radius;
      MAG = o.magnify;
      w = root.offsetWidth;
      h = root.offsetHeight;
      const want = Math.min(window.devicePixelRatio || 1, 2);
      dpr = w * h * want * want > MAX_PIXELS ? Math.max(0.5, Math.sqrt(MAX_PIXELS / Math.max(1, w * h))) : want;
      const cw = Math.max(1, Math.round(w * dpr)), ch = Math.max(1, Math.round(h * dpr));
      if (canvas.width !== cw) canvas.width = cw;
      if (canvas.height !== ch) canvas.height = ch;
      nx = Math.max(1, Math.floor(w / G));
      ny = Math.max(1, Math.floor(h / G));
      // Lines that are an odd number of screen pixels thick sit on half pixels, so they stay crisp.
      const half = Math.round(LINE_W * dpr) % 2 ? 0.5 : 0;
      ox = (Math.round(((w - (nx - 1) * G) / 2) * dpr) + half) / dpr;
      oy = (Math.round(((h - (ny - 1) * G) / 2) * dpr) + half) / dpr;
    };

    // Where a point of the grid lands under the loupe, and how lit it is (0 to 1).
    const at = { x: 0, y: 0, t: 0 };
    const warp = (px: number, py: number) => {
      at.x = px;
      at.y = py;
      at.t = 0;
      if (L.s <= 0) return;
      const dx = px - L.x, dy = py - L.y, d2 = dx * dx + dy * dy;
      if (d2 >= R * R) return;
      const u = Math.sqrt(d2) / R, k = 1 - u;
      at.t = k * k * (1 + 2 * u) * L.s; // smooth: full at the pointer, nothing at the rim
      if (still) return;
      const push = PUSH * k * k * L.s; // spreads from the middle, never past the rim
      at.x = px + dx * push;
      at.y = py + dy * push;
    };

    const loupeBox = (): Box => {
      const m = GLOW_R * MAG + PLUS_ARM * MAG + 4;
      return { x0: L.x - R - m, y0: L.y - R - m, x1: L.x + R + m, y1: L.y + R + m };
    };

    const linePaths: Path2D[] = [];
    const drawLines = (x0: number, y0: number, x1: number, y1: number) => {
      const rest = new Path2D();
      for (let i = 0; i <= LEVELS; i++) linePaths[i] = new Path2D();
      const lit = L.s > 0;
      // One line, from a to b along it; `vert` says which way it runs.
      const line = (c: number, a: number, b: number, vert: boolean) => {
        const pc = vert ? L.x : L.y, pa = vert ? L.y : L.x;
        const near = lit && Math.abs(c - pc) < R;
        const la = near ? Math.max(a, pa - R) : b, lb = near ? Math.min(b, pa + R) : b;
        const seg = (p: Path2D, s0: number, s1: number) => {
          if (s1 <= s0) return;
          if (vert) { p.moveTo(c, s0); p.lineTo(c, s1); } else { p.moveTo(s0, c); p.lineTo(s1, c); }
        };
        if (!near || lb <= la) return seg(rest, a, b);
        seg(rest, a, la);
        seg(rest, lb, b);
        // Inside the loupe: short pieces that bend with the marks and light up near the pointer.
        let px = 0, py = 0, pt = 0;
        for (let s = la, first = true; ; s = Math.min(lb, s + STEP)) {
          if (vert) warp(c, s); else warp(s, c);
          if (!first) {
            const lvl = Math.round(((pt + at.t) / 2) * LEVELS);
            const p = lvl > 0 ? linePaths[lvl] : rest;
            p.moveTo(px, py);
            p.lineTo(at.x, at.y);
          }
          px = at.x; py = at.y; pt = at.t; first = false;
          if (s >= lb) break;
        }
      };
      const ia = Math.max(0, Math.floor((x0 - ox) / G)), ib = Math.min(nx - 1, Math.ceil((x1 - ox) / G));
      for (let i = ia; i <= ib; i++) line(ox + i * G, Math.max(0, y0), Math.min(h, y1), true);
      const ja = Math.max(0, Math.floor((y0 - oy) / G)), jb = Math.min(ny - 1, Math.ceil((y1 - oy) / G));
      for (let j = ja; j <= jb; j++) line(oy + j * G, Math.max(0, x0), Math.min(w, x1), false);
      ctx.lineWidth = LINE_W;
      ctx.lineCap = "butt";
      ctx.strokeStyle = mix(base, hot, 0, LINE_A * base[3], 0);
      ctx.stroke(rest);
      for (let i = 1; i <= LEVELS; i++) {
        ctx.strokeStyle = mix(base, hot, i / LEVELS, LINE_A * base[3], LINE_HOT_A * hot[3]);
        ctx.stroke(linePaths[i]);
      }
    };

    const drawMarks = (x0: number, y0: number, x1: number, y1: number) => {
      const plus = kind === "plus" || kind === "plus-lines";
      const m = GLOW_R * MAG + PLUS_ARM * MAG;
      const ia = Math.max(0, Math.floor((x0 - m - ox) / G)), ib = Math.min(nx - 1, Math.ceil((x1 + m - ox) / G));
      const ja = Math.max(0, Math.floor((y0 - m - oy) / G)), jb = Math.min(ny - 1, Math.ceil((y1 + m - oy) / G));
      const rest = new Path2D();
      const lit: number[] = [];
      for (let j = ja; j <= jb; j++) {
        for (let i = ia; i <= ib; i++) {
          warp(ox + i * G, oy + j * G);
          if (at.t > 0.002) {
            lit.push(at.x, at.y, at.t);
          } else if (plus) {
            rest.moveTo(at.x - PLUS_ARM, at.y); rest.lineTo(at.x + PLUS_ARM, at.y);
            rest.moveTo(at.x, at.y - PLUS_ARM); rest.lineTo(at.x, at.y + PLUS_ARM);
          } else {
            rest.moveTo(at.x + DOT_R, at.y);
            rest.arc(at.x, at.y, DOT_R, 0, Math.PI * 2);
          }
        }
      }
      const restStyle = mix(base, hot, 0, MARK_A * base[3], 0);
      if (plus) {
        ctx.lineWidth = PLUS_W;
        ctx.lineCap = "butt";
        ctx.strokeStyle = restStyle;
        ctx.stroke(rest);
      } else {
        ctx.fillStyle = restStyle;
        ctx.fill(rest);
      }
      // Lit marks: a soft glow first, then the mark, grown and in the hover color.
      for (let k = 0; k < lit.length; k += 3) {
        const x = lit[k], y = lit[k + 1], t = lit[k + 2];
        const sc = still ? 1 : 1 + (MAG - 1) * t;
        if (sprite && glowA > 0) {
          const g = GLOW_R * sc;
          ctx.globalAlpha = glowA * t;
          ctx.drawImage(sprite, x - g, y - g, g * 2, g * 2);
          ctx.globalAlpha = 1;
        }
        const style = mix(base, hot, t, MARK_A * base[3], hot[3]);
        ctx.beginPath();
        if (plus) {
          const a = PLUS_ARM * sc;
          ctx.moveTo(x - a, y); ctx.lineTo(x + a, y);
          ctx.moveTo(x, y - a); ctx.lineTo(x, y + a);
          ctx.lineWidth = PLUS_W * (1 + (sc - 1) * 0.5);
          ctx.strokeStyle = style;
          ctx.stroke();
        } else {
          ctx.arc(x, y, DOT_R * sc, 0, Math.PI * 2);
          ctx.fillStyle = style;
          ctx.fill();
        }
      }
    };

    // Redraw one part of the box (in box pixels), lined up with screen pixels so no seams show.
    const paint = (b: Box) => {
      const X0 = Math.max(0, Math.floor(b.x0 * dpr)), Y0 = Math.max(0, Math.floor(b.y0 * dpr));
      const X1 = Math.min(canvas.width, Math.ceil(b.x1 * dpr)), Y1 = Math.min(canvas.height, Math.ceil(b.y1 * dpr));
      if (X1 <= X0 || Y1 <= Y0) return;
      ctx.save();
      ctx.setTransform(1, 0, 0, 1, 0, 0);
      ctx.beginPath();
      ctx.rect(X0, Y0, X1 - X0, Y1 - Y0);
      ctx.clip();
      ctx.clearRect(X0, Y0, X1 - X0, Y1 - Y0);
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
      const x0 = X0 / dpr, y0 = Y0 / dpr, x1 = X1 / dpr, y1 = Y1 / dpr;
      if (kind === "plus-lines" || kind === "dots-lines") drawLines(x0, y0, x1, y1);
      drawMarks(x0, y0, x1, y1);
      ctx.restore();
    };

    const paintAll = () => {
      if (!ready) return;
      layout();
      readColors();
      paint({ x0: 0, y0: 0, x1: w, y1: h });
      drawn = L.s > 0 ? loupeBox() : null;
    };

    const frame = (now: number) => {
      raf = 0;
      const dt = Math.min(64, last ? now - last : 16);
      last = now;
      // The pointer in the box's own pixels (offsetWidth ignores scaling, so this also works inside a scaled preview).
      const r = root.getBoundingClientRect();
      const sx = w ? r.width / w || 1 : 1, sy = h ? r.height / h || 1 : 1;
      const lx = (P.cx - r.left) / sx, ly = (P.cy - r.top) / sy;
      const inside = P.has && visible && lx >= 0 && ly >= 0 && lx <= w && ly <= h;
      const target = inside ? 1 : 0;
      if (inside && L.s < 0.02) {
        L.x = lx; // it appears where the pointer is, never slides in from where it left
        L.y = ly;
      } else if (inside) {
        const f = 1 - Math.exp(-dt / FOLLOW_MS);
        L.x += (lx - L.x) * f;
        L.y += (ly - L.y) * f;
      }
      // Eases in and out along a smooth S curve over a set time, so it starts and ends softly and always finishes.
      L.p = target > L.p ? Math.min(1, L.p + dt / IN_MS) : Math.max(0, L.p - dt / OUT_MS);
      L.s = L.p * L.p * (3 - 2 * L.p);
      const settled = L.p === target && (!inside || Math.hypot(lx - L.x, ly - L.y) < 0.15);
      const box = L.s > 0 ? loupeBox() : null;
      if (drawn) paint(drawn);
      if (box) paint(box);
      drawn = box;
      if (!settled) raf = requestAnimationFrame(frame);
      else last = 0;
    };

    const wake = () => {
      if (!raf && ready && (visible || L.s > 0)) raf = requestAnimationFrame(frame);
    };

    /* Pointer: listened to on the whole window, so content on top never blocks it and nothing here blocks a click. */
    const onMove = (e: PointerEvent) => {
      P.cx = e.clientX;
      P.cy = e.clientY;
      if (e.pointerType !== "touch" || e.buttons) {
        clearTimeout(holdTimer);
        P.has = true;
      }
      wake();
    };
    const onDown = (e: PointerEvent) => {
      if (e.pointerType !== "touch") return;
      clearTimeout(holdTimer);
      P.cx = e.clientX;
      P.cy = e.clientY;
      P.has = true;
      wake();
    };
    const onUp = (e: PointerEvent) => {
      if (e.pointerType !== "touch") return;
      clearTimeout(holdTimer);
      holdTimer = window.setTimeout(() => {
        P.has = false;
        wake();
      }, TOUCH_HOLD_MS);
    };
    const onLeave = (e: PointerEvent) => {
      // A mouse leaving the window. (A finger "leaves" on every lift; onUp handles that.)
      if (e.relatedTarget || e.pointerType === "touch") return;
      P.has = false;
      wake();
    };
    const onBlur = () => {
      P.has = false;
      wake();
    };
    const onScroll = () => {
      if (P.has || L.s > 0) wake();
    };
    // Browser zoom changes the pixel ratio without changing the box size.
    let lastDpr = window.devicePixelRatio;
    const onResize = () => {
      if (window.devicePixelRatio !== lastDpr) {
        lastDpr = window.devicePixelRatio;
        paintAll();
      }
    };
    const onReduce = () => {
      still = reduceMq.matches;
      paintAll();
    };

    window.addEventListener("pointermove", onMove, { passive: true });
    window.addEventListener("pointerdown", onDown, { passive: true });
    window.addEventListener("pointerup", onUp, { passive: true });
    window.addEventListener("pointercancel", onUp, { passive: true });
    document.addEventListener("pointerout", onLeave, { passive: true });
    window.addEventListener("blur", onBlur);
    window.addEventListener("scroll", onScroll, { passive: true, capture: true });
    window.addEventListener("resize", onResize);
    reduceMq.addEventListener("change", onReduce);

    // Draws only once it comes near the screen; ignores the pointer while away.
    const io = new IntersectionObserver(
      ([entry]) => {
        visible = entry.isIntersecting;
        if (visible && !ready) {
          ready = true;
          paintAll();
        }
        if (!visible && L.s > 0) {
          cancelAnimationFrame(raf);
          raf = 0;
          L.p = L.s = 0;
          if (drawn) paint(drawn);
          drawn = null;
        }
        wake();
      },
      { rootMargin: "200px" },
    );
    io.observe(root);

    let lastW = -1, lastH = -1;
    const ro = new ResizeObserver(() => {
      if (root.offsetWidth === lastW && root.offsetHeight === lastH) return;
      lastW = root.offsetWidth;
      lastH = root.offsetHeight;
      paintAll();
    });
    ro.observe(root);

    // Colors follow the theme: a class or data-theme change on the page, or the system switching.
    const mo = new MutationObserver(paintAll);
    mo.observe(document.documentElement, { attributes: true, attributeFilter: ["class", "style", "data-theme"] });
    const darkMq = matchMedia("(prefers-color-scheme: dark)");
    darkMq.addEventListener("change", paintAll);

    refresh.current = paintAll;

    return () => {
      refresh.current = () => {};
      cancelAnimationFrame(raf);
      clearTimeout(holdTimer);
      window.removeEventListener("pointermove", onMove);
      window.removeEventListener("pointerdown", onDown);
      window.removeEventListener("pointerup", onUp);
      window.removeEventListener("pointercancel", onUp);
      document.removeEventListener("pointerout", onLeave);
      window.removeEventListener("blur", onBlur);
      window.removeEventListener("scroll", onScroll, { capture: true });
      window.removeEventListener("resize", onResize);
      reduceMq.removeEventListener("change", onReduce);
      darkMq.removeEventListener("change", paintAll);
      io.disconnect();
      ro.disconnect();
      mo.disconnect();
    };
  }, []);

  return (
    <div ref={rootRef} className={className ? `ilg ${className}` : "ilg"} {...rest}>
      <style>{CSS}</style>
      <div ref={layerRef} className="ilg-layer" aria-hidden="true">
        <canvas ref={canvasRef} width={0} height={0} />
      </div>
      {children}
    </div>
  );
}

export default LoupeGrid;
```

Usage

Wrap a section's content in it and give it a size. Everything inside sits above the grid.

"use client";
import { LoupeGrid } from "@/components/ui/loupe-grid";

export function Hero() {
  return (
    <LoupeGrid
      type="dots-lines"
      hoverColor="var(--primary)"   // optional: the color marks turn under the pointer
      className="flex min-h-[560px] flex-col items-center justify-center gap-6 bg-background px-6"
    >
      <h1 className="text-5xl font-semibold tracking-tight">Ship the calm version</h1>
      <a href="/signup" className="rounded-full bg-foreground px-5 py-2.5 text-background">
        Get started
      </a>
    </LoupeGrid>
  );
}

For a whole page, leave it empty and fix it to the screen, so it stays one screen big however long the page is.

// Behind a whole page: fixed to the screen, under everything.
<LoupeGrid type="plus" className="fixed inset-0 -z-10" />

How it reacts

At rest it is a faint, even grid. Under the pointer it works like a loupe: the marks within radius swell, light up and spread apart a little.

The mark right under the pointer grows the most and turns fully into the hover color, with a soft glow behind it. Marks farther out grow less and keep more of their faint color, fading smoothly to nothing at the edge of the loupe, so there is never a hard ring. The marks spread a few pixels away from the pointer, and on the types with lines the lines bend with them and brighten too. The loupe trails the pointer by a hair, eases in quickly when the pointer arrives and fades out slowly when it leaves. It listens to the pointer across the whole page, so it reacts under your headline and buttons too, and it never catches a click or a text selection. On a phone it shows where your finger touches and fades shortly after you lift it. With reduced motion the marks still light up and glow, but they don't grow or move. Nothing runs while it is at rest or off screen.

Props

PropDefaultWhat it does
type"plus"Which marks: "plus", "plus-lines", "dots" or "dots-lines". The lines join the marks into a grid.
gap56Distance between marks, in px (12 to 400). The grid is centred, so the edges always match.
radius150How far the loupe reaches from the pointer, in px. Marks farther away stay still.
magnify1.8How big the mark right under the pointer grows (1.8 is 80% bigger). 1 turns the growing off; it still lights up.
colorthe text colorColor of the marks and lines at rest. Marks are drawn at 30% of it and lines at 10%, so pass a full color.
hoverColorthe text colorColor the marks turn near the pointer, and their soft glow. A brand color works well here.
children—Your content. It sits above the grid and works as normal: text can be selected and buttons clicked.
className / style—On the box. Give it a size (or fill its parent), and a background color if you want one: the grid has none.