Scratch card in React: a canvas foil that reveals a coupon

Build a scratch-to-reveal coupon in React with a canvas: destination-out strokes, sampling how much is cleared, a falling foil and an accessible reveal button.

6 min read

The real component. Click the picture to open it live and try it before you read how it was built.

A discount you scratch for feels earned. The effect is simple once you know the one canvas setting that makes it work.

Paint the foil, then erase it

Draw the foil once as a silver gradient. Then switch the canvas to globalCompositeOperation = 'destination-out'. From that moment every stroke you draw removes pixels instead of adding them, so the code underneath shows through wherever the pointer has been.

src/registry/announcement-bars/scratch/use-scratch-foil.ts

"use client";

import { useEffect, useRef, useState, type PointerEvent, type RefObject } from "react";

const BRUSH = 14;
// How much of the foil has to be gone, as a share, before the rest falls away.
const CLEARED_AT = 0.45;
// Only every few pixels are counted when measuring how much is gone; plenty for a share, and cheap.
const SAMPLE_STEP = 8;
const ALPHA = 3;
const CHANNELS = 4;

// Paints a brushed-silver foil over the canvas's box, at the screen's pixel ratio.
function paintFoil(canvas: HTMLCanvasElement): CanvasRenderingContext2D | null {
  const context = canvas.getContext("2d");
  if (!context) return null;
  const ratio = Math.min(window.devicePixelRatio || 1, 2);
  const { width, height } = canvas.getBoundingClientRect();
  canvas.width = Math.round(width * ratio);
  canvas.height = Math.round(height * ratio);
  context.scale(ratio, ratio);
  const sheen = context.createLinearGradient(0, 0, width, height);
  sheen.addColorStop(0, "#9ca3af");
  sheen.addColorStop(0.45, "#f3f4f6");
  sheen.addColorStop(0.55, "#d1d5db");
  sheen.addColorStop(1, "#9ca3af");
  context.fillStyle = sheen;
  context.fillRect(0, 0, width, height);
  context.globalCompositeOperation = "destination-out";
  context.lineCap = "round";
  context.lineJoin = "round";
  context.lineWidth = BRUSH * 2;
  return context;
}

// The share of the foil already scratched away.
function clearedShare(context: CanvasRenderingContext2D): number {
  const { width, height } = context.canvas;
  const pixels = context.getImageData(0, 0, width, height).data;
  let clear = 0;
  let total = 0;
  for (let index = ALPHA; index < pixels.length; index += CHANNELS * SAMPLE_STEP) {
    total += 1;
    if (pixels[index] === 0) clear += 1;
  }
  return total ? clear / total : 0;
}

// A scratch-off foil on a canvas: drag across it to scratch, and once enough is gone `isCleared` turns true so the
// rest can fall away. Returns the pointer handlers to put on the canvas.
export function useScratchFoil(canvasRef: RefObject<HTMLCanvasElement | null>) {
  const contextRef = useRef<CanvasRenderingContext2D | null>(null);
  const last = useRef<{ x: number; y: number } | null>(null);
  const [isCleared, setIsCleared] = useState(false);

  useEffect(() => {
    if (canvasRef.current) contextRef.current = paintFoil(canvasRef.current);
  }, [canvasRef]);

  function scratch(event: PointerEvent<HTMLCanvasElement>) {
    const context = contextRef.current;
    if (!context || isCleared || event.buttons === 0) return;
    const box = event.currentTarget.getBoundingClientRect();
    const point = { x: event.clientX - box.left, y: event.clientY - box.top };
    context.beginPath();
    context.moveTo(last.current?.x ?? point.x, last.current?.y ?? point.y);
    context.lineTo(point.x, point.y);
    context.stroke();
    last.current = point;
  }

  function finish() {
    last.current = null;
    if (contextRef.current && clearedShare(contextRef.current) >= CLEARED_AT) setIsCleared(true);
  }

  return {
    isCleared,
    reveal: () => setIsCleared(true),
    handlers: {
      onPointerDown: (event: PointerEvent<HTMLCanvasElement>) => {
        event.currentTarget.setPointerCapture(event.pointerId);
        scratch(event);
      },
      onPointerMove: scratch,
      onPointerUp: finish,
      onPointerCancel: finish,
    },
  };
}
The hook: paint, scratch with round strokes, measure what's gone

Strokes, not dots

Pointer events arrive in jumps on a fast swipe. Drawing a dot per event leaves gaps, so each move draws a round-capped line from the last point to the new one. setPointerCapture keeps the stroke going even if the finger slides off the strip.

Knowing when it's done

When the pointer lifts, read the pixels and count how many are transparent. Sampling every eighth pixel is plenty for a percentage and keeps it cheap. Past 45 percent the rest of the foil falls away with a small rotate, and a copy button appears.

Don't lock anyone out

  • The canvas is decorative; the code is real text underneath.
  • A 'Just show me' button reveals it at once for keyboards and screen readers.
  • Copy uses the clipboard API with a copied state.

src/registry/announcement-bars/scratch/announcement-scratch.tsx

"use client";

import { useRef } from "react";
import { AnimatePresence, motion } from "motion/react";
import { Check, Copy } from "lucide-react";
import { useCopyToClipboard } from "@/hooks/use-copy-to-clipboard";
import { usePrefersReducedMotion } from "@/hooks/use-prefers-reduced-motion";
import { cn } from "@/lib/utils";
import { useScratchFoil } from "./use-scratch-foil";

export interface AnnouncementScratchProps {
  // Before the strip: "Scratch for this week's discount".
  label: string;
  // The code under the foil, and what it's worth.
  code: string;
  value: string;
  // The button that reveals the code without scratching, for keyboards and screen readers.
  revealLabel: string;
  className?: string;
}

// A discount you scratch for. A strip of brushed-silver foil sits in the bar; scratch it with a mouse or a finger and
// the code shows through. Once enough is gone the rest of the foil falls away and the code can be copied. A button
// beside it reveals the code at once.
export function AnnouncementScratch({ label, code, value, revealLabel, className }: AnnouncementScratchProps) {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const { isCleared, reveal, handlers } = useScratchFoil(canvasRef);
  const { isCopied, copy } = useCopyToClipboard();
  const isReduced = usePrefersReducedMotion();
  return (
    <div className={cn("bg-rose-600 text-white", className)}>
      <div className="mx-auto flex min-h-12 max-w-6xl flex-wrap items-center justify-center gap-x-4 gap-y-2 px-4 py-2 text-sm">
        <p className="font-medium">{label}</p>
        <div className="relative h-8 w-44 overflow-hidden rounded-md bg-white text-rose-700 ring-2 ring-white/60">
          <p className="flex h-full items-center justify-center gap-2 font-mono text-sm font-bold tracking-widest">
            {code}
            <span className="font-sans text-xs font-medium tracking-normal text-rose-500">{value}</span>
          </p>
          <AnimatePresence>
            {isCleared ? null : (
              <motion.canvas
                key="foil"
                ref={canvasRef}
                aria-hidden
                exit={isReduced ? { opacity: 0 } : { opacity: 0, y: 12, rotate: 4 }}
                transition={{ duration: 0.4 }}
                className="absolute inset-0 size-full cursor-crosshair touch-none"
                {...handlers}
              />
            )}
          </AnimatePresence>
        </div>
        {isCleared ? (
          <button
            type="button"
            onClick={() => copy(code)}
            className="inline-flex items-center gap-1.5 rounded-md bg-white/15 px-2.5 py-1 text-xs font-semibold outline-none hover:bg-white/25 focus-visible:ring-2 focus-visible:ring-white"
          >
            {isCopied ? <Check aria-hidden className="size-3.5" /> : <Copy aria-hidden className="size-3.5" />}
            {isCopied ? "Copied" : "Copy code"}
          </button>
        ) : (
          <button
            type="button"
            onClick={reveal}
            className="rounded-md px-2 py-1 text-xs font-medium text-white/80 underline underline-offset-4 outline-none hover:text-white focus-visible:ring-2 focus-visible:ring-white"
          >
            {revealLabel}
          </button>
        )}
      </div>
    </div>
  );
}
The bar around the foil

More articles