Skip to content

Peel Card

A DOM card that curls back like paper to reveal its back.

Experimental · Chrome origin trialChecking support…

Built on the WICG HTML-in-Canvas proposal, which is not a web standard and changes between Chrome versions. Every component works without it: other browsers get the same live DOM with a CSS approximation of the effect.

To try the native version locally, open Chrome Canary and enable chrome://flags/#canvas-draw-element. In production, register for the origin trial and set NEXT_PUBLIC_HTML_IN_CANVAS_OT_TOKEN.

Installation

CLI

npx shadcn@latest add https://hantui-theta.vercel.app/r/peel-card.json

Manual

  1. Install the dependencies

    npm install clsx motion tailwind-merge
  2. Add the shared helpers

    Components use cn() from lib/utils.ts and the motion tokens below. See Installation if you have not set them up yet.

    lib/html-canvas/gl.ts
    /**
     * Small WebGL2 helpers shared by the HTML-in-Canvas components. Shaders work in the canvas's CSS
     * pixels, so a DOMMatrix used to draw an element is the same one passed to `syncElementGeometry`.
     */
    
    /**
     * GLSL: projects a CSS-px position (already multiplied by the draw matrix, so it may carry a
     * perspective w) to clip space. Keeps w for perspective-correct texturing. Needs `uniform vec2 u_canvas`.
     */
    export const PROJECT_GLSL = /* glsl */ `
    uniform vec2 u_canvas;
    vec4 projectCss(vec4 q) {
      return vec4(2.0 * q.x / u_canvas.x - q.w, -(2.0 * q.y / u_canvas.y - q.w), 0.0, q.w);
    }`;
    
    /** GLSL: signed distance to a rounded rectangle centered at the origin (half size `b`, radius `r`). */
    export const ROUND_RECT_GLSL = /* glsl */ `
    float sdRoundRect(vec2 p, vec2 b, float r) {
      vec2 q = abs(p) - b + r;
      return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - r;
    }`;
    
    function compile(gl: WebGL2RenderingContext, type: number, source: string) {
      const shader = gl.createShader(type);
      if (!shader) throw new Error("Could not create a shader");
      gl.shaderSource(shader, source);
      gl.compileShader(shader);
      if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS) && !gl.isContextLost()) {
        const log = gl.getShaderInfoLog(shader);
        gl.deleteShader(shader);
        throw new Error(`Shader compile failed: ${log}`);
      }
      return shader;
    }
    
    export interface Program {
      program: WebGLProgram;
      /** Cached uniform location lookup. */
      u: (name: string) => WebGLUniformLocation | null;
    }
    
    /** Compiles and links a program. Attribute 0 is always `a_pos`. */
    export function createProgram(gl: WebGL2RenderingContext, vertex: string, fragment: string): Program {
      const program = gl.createProgram();
      if (!program) throw new Error("Could not create a program");
      gl.attachShader(program, compile(gl, gl.VERTEX_SHADER, vertex));
      gl.attachShader(program, compile(gl, gl.FRAGMENT_SHADER, fragment));
      gl.bindAttribLocation(program, 0, "a_pos");
      gl.linkProgram(program);
      if (!gl.getProgramParameter(program, gl.LINK_STATUS) && !gl.isContextLost()) throw new Error(`Program link failed: ${gl.getProgramInfoLog(program)}`);
      const cache = new Map<string, WebGLUniformLocation | null>();
      return {
        program,
        u: (name) => {
          if (!cache.has(name)) cache.set(name, gl.getUniformLocation(program, name));
          return cache.get(name) ?? null;
        },
      };
    }
    
    export interface Mesh {
      vao: WebGLVertexArrayObject;
      count: number;
    }
    
    /** A unit grid over [0, 1]² as indexed triangles, in attribute 0. One cell is a plain quad. */
    export function createGrid(gl: WebGL2RenderingContext, cols = 1, rows = 1): Mesh {
      const vao = gl.createVertexArray();
      if (!vao) throw new Error("Could not create a vertex array");
      gl.bindVertexArray(vao);
      const positions: number[] = [];
      for (let y = 0; y <= rows; y++) for (let x = 0; x <= cols; x++) positions.push(x / cols, y / rows);
      const indices: number[] = [];
      for (let y = 0; y < rows; y++) {
        for (let x = 0; x < cols; x++) {
          const i = y * (cols + 1) + x;
          indices.push(i, i + 1, i + cols + 1, i + 1, i + cols + 2, i + cols + 1);
        }
      }
      const vbo = gl.createBuffer();
      gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
      gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);
      gl.enableVertexAttribArray(0);
      gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
      const ibo = gl.createBuffer();
      gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, ibo);
      gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint32Array(indices), gl.STATIC_DRAW);
      gl.bindVertexArray(null);
      return { vao, count: indices.length };
    }
    
    /** Draws a mesh from `createGrid`. */
    export function drawMesh(gl: WebGL2RenderingContext, mesh: Mesh, instances = 0) {
      gl.bindVertexArray(mesh.vao);
      if (instances > 0) gl.drawElementsInstanced(gl.TRIANGLES, mesh.count, gl.UNSIGNED_INT, 0, instances);
      else gl.drawElements(gl.TRIANGLES, mesh.count, gl.UNSIGNED_INT, 0);
      gl.bindVertexArray(null);
    }
    
    /** Uploads a DOMMatrix to a mat4 uniform. */
    export function setMatrix(gl: WebGL2RenderingContext, location: WebGLUniformLocation | null, matrix: DOMMatrix) {
      gl.uniformMatrix4fv(location, false, matrix.toFloat32Array());
    }
    
    /** Parses "#rrggbb" into 0–1 RGB. */
    export function rgb(hex: string): [number, number, number] {
      const h = hex.replace("#", "");
      const n = Number.parseInt(h.length === 3 ? h.replace(/./g, (c) => c + c) : h, 16) || 0;
      return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255];
    }
    lib/html-canvas/setup.ts
    import type { HtmlCanvasSupport } from "@/lib/html-canvas/support";
    
    /* eslint-disable @typescript-eslint/no-explicit-any -- the API is not in lib.dom yet */
    
    /**
     * Attributes that make a canvas lay out and paint its children, for use in JSX so the canvas is
     * drawable from its first layout: `content="drawable"` on 155+, `layoutsubtree` before that.
     */
    export function drawableCanvasAttributes(support: HtmlCanvasSupport): Record<string, string> {
      if (support.version === "155+") return { content: "drawable" };
      if (support.version === "none") return {};
      return { layoutsubtree: "" };
    }
    
    /** Makes a canvas drawable after the fact (idempotent). */
    export function prepareDrawableCanvas(canvas: HTMLCanvasElement) {
      const c = canvas as any;
      if ("content" in HTMLCanvasElement.prototype) {
        if (canvas.getAttribute("content") !== "drawable") canvas.setAttribute("content", "drawable");
      } else if (!canvas.hasAttribute("layoutsubtree")) {
        canvas.setAttribute("layoutsubtree", "");
        if ("layoutSubtree" in c) c.layoutSubtree = true;
      }
    }
    
    /**
     * Attributes for an element the canvas draws on its own. On 155+ it must carry `drawable`; on older
     * versions it must instead be a direct child of the canvas, which callers arrange in their markup.
     */
    export function drawableElementAttributes(support: HtmlCanvasSupport): Record<string, string> {
      return support.version === "155+" ? { drawable: "" } : {};
    }
    
    /** Asks the canvas for a `paint` event on the next frame, where supported. */
    export function requestCanvasPaint(canvas: HTMLCanvasElement) {
      const c = canvas as any;
      if (typeof c.requestPaint === "function") c.requestPaint();
    }
    /* eslint-enable @typescript-eslint/no-explicit-any */
    lib/html-canvas/support.ts
    /**
     * Feature detection for the experimental HTML-in-Canvas API (WICG html-in-canvas). The API is a
     * Chrome origin trial, not a standard, and its shape changed in Chrome 150 and 155. Nothing outside
     * `src/lib/html-canvas/` may touch it: every call goes through these adapters.
     *
     * - 155+: `content="drawable"`, `drawable` descendants, `texElementSubImage2D`,
     *   `canvas.updateElementGeometry()` and automatic hit-testing for 2D draws.
     * - 150–154: `layoutsubtree`, `drawElementImage()` returning a DOMMatrix, `texElementImage2D(target,
     *   internalformat, element)` and `canvas.getElementTransform(element, drawTransform)`.
     * - legacy (< 150): `texElementImage2D(target, level, internalformat, format, type, element)`.
     */
    
    export type HtmlCanvasVersion = "155+" | "150-154" | "legacy" | "none";
    
    export interface HtmlCanvasSupport {
      /** `drawElementImage` on 2D contexts. */
      twoD: boolean;
      /** Element textures in WebGL2. */
      webgl: boolean;
      /** Element textures in WebGPU. */
      webgpu: boolean;
      version: HtmlCanvasVersion;
    }
    
    export const NO_SUPPORT: HtmlCanvasSupport = { twoD: false, webgl: false, webgpu: false, version: "none" };
    
    /* eslint-disable @typescript-eslint/no-explicit-any -- the API is not in lib.dom yet */
    let cached: HtmlCanvasSupport | null = null;
    
    /** What this browser supports. Always "none" on the server. Cached after the first call. */
    export function getHtmlCanvasSupport(): HtmlCanvasSupport {
      if (typeof window === "undefined" || typeof HTMLCanvasElement === "undefined") return NO_SUPPORT;
      if (cached) return cached;
      const canvasProto = HTMLCanvasElement.prototype as any;
      const ctx2d = typeof CanvasRenderingContext2D !== "undefined" ? (CanvasRenderingContext2D.prototype as any) : {};
      const gl2 = typeof WebGL2RenderingContext !== "undefined" ? (WebGL2RenderingContext.prototype as any) : {};
      const gpuQueue = typeof (window as any).GPUQueue !== "undefined" ? (window as any).GPUQueue.prototype : {};
    
      const twoD = "drawElementImage" in ctx2d;
      const sub = "texElementSubImage2D" in gl2;
      const tex = "texElementImage2D" in gl2;
      const webgpu = "drawElementImageToTexture" in gpuQueue || "copyElementImageToTexture" in gpuQueue;
    
      let version: HtmlCanvasVersion = "none";
      if (sub || "content" in canvasProto || "updateElementGeometry" in canvasProto) version = "155+";
      else if (tex) version = typeof gl2.texElementImage2D === "function" && gl2.texElementImage2D.length >= 6 ? "legacy" : "150-154";
      else if (twoD || "layoutSubtree" in canvasProto) version = "150-154";
    
      cached = { twoD, webgl: sub || tex, webgpu, version };
      return cached;
    }
    
    /** True when the API can draw into the given context type. */
    export function supportsContext(support: HtmlCanvasSupport, context: "2d" | "webgl2") {
      return support.version !== "none" && (context === "2d" ? support.twoD : support.webgl);
    }
    
    /** A short label for status chips: "Chrome 150–154 API". */
    export function describeSupport(support: HtmlCanvasSupport) {
      if (support.version === "none") return "Not supported";
      return { "155+": "Chrome 155+ API", "150-154": "Chrome 150–154 API", legacy: "Pre-150 API" }[support.version];
    }
    /* eslint-enable @typescript-eslint/no-explicit-any */
    lib/html-canvas/sync-geometry.ts
    import { getHtmlCanvasSupport } from "@/lib/html-canvas/support";
    
    /* eslint-disable @typescript-eslint/no-explicit-any -- the API is not in lib.dom yet */
    
    /**
     * Tells the browser where an element is drawn, so clicks, text selection, focus rings and screen
     * reader focus land on the drawn pixels. `canvasTransform` maps the element's own CSS px (origin at
     * its top-left) to the canvas's CSS px, and may include perspective; it is converted to the device
     * pixels the API expects.
     *
     * Canvas children are laid out at the canvas's top-left corner (they do not stack), so the transform
     * is the element's whole position.
     *
     * For non-affine warps (ripples, curls, cloth), pass the closest affine approximation and calm the
     * warp while an input inside the element has focus.
     */
    export function syncElementGeometry(canvas: HTMLCanvasElement, element: HTMLElement, canvasTransform: DOMMatrix) {
      const c = canvas as any;
      const support = getHtmlCanvasSupport();
      const cssWidth = canvas.clientWidth || canvas.width;
      const cssHeight = canvas.clientHeight || canvas.height;
      // The API works in device pixels on both sides (the element's rendered image and the canvas's backing
      // store), so the CSS-px matrix is conjugated by the pixel ratio: S · M · S⁻¹.
      const toBackingStore = new DOMMatrix().scale(canvas.width / cssWidth, canvas.height / cssHeight, 1);
      const pixels = toBackingStore.multiply(canvasTransform).multiply(toBackingStore.inverse());
      try {
        if (support.version === "155+" && typeof c.updateElementGeometry === "function") {
          c.updateElementGeometry(element, { canvasTransform: pixels });
          return;
        }
        if (typeof c.getElementTransform === "function") {
          element.style.transform = c.getElementTransform(element, pixels).toString();
          return;
        }
      } catch {
        // Fall through to the manual mapping below.
      }
      // Manual: children sit at the canvas origin, so the CSS-px transform applies as is.
      element.style.transformOrigin = "0 0";
      element.style.transform = canvasTransform.toString();
    }
    
    /** Clears geometry set by `syncElementGeometry` or a legacy `drawElement2D`. */
    export function clearElementGeometry(element: HTMLElement) {
      element.style.transform = "";
      element.style.transformOrigin = "";
    }
    
    /** A CSS-px perspective matrix, like `perspective(d)` in CSS. */
    export function perspective(distance: number) {
      return new DOMMatrix([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, -1 / distance, 0, 0, 0, 1]);
    }
    /* eslint-enable @typescript-eslint/no-explicit-any */
    lib/html-canvas/texture-webgl.ts
    import { getHtmlCanvasSupport } from "@/lib/html-canvas/support";
    
    /* eslint-disable @typescript-eslint/no-explicit-any -- the API is not in lib.dom yet */
    
    /** A WebGL texture that holds a live element's pixels. */
    export interface ElementTexture {
      texture: WebGLTexture;
      /** Natural size of the last upload, in CSS px. */
      width: number;
      height: number;
      /** Allocated size on 155+, where the storage is reused until the element resizes. */
      allocated: { width: number; height: number } | null;
    }
    
    /** Creates an empty, linearly filtered, edge-clamped texture for `uploadElementTexture`. */
    export function createElementTexture(gl: WebGL2RenderingContext): ElementTexture {
      const texture = gl.createTexture();
      if (!texture) throw new Error("Could not create a texture");
      gl.bindTexture(gl.TEXTURE_2D, texture);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
      return { texture, width: 0, height: 0, allocated: null };
    }
    
    /**
     * Uploads an element's current rendering into `target`. Call it from the canvas `paint` event or on
     * resize, never every frame. Returns false when the element could not be uploaded.
     *
     * - 155+: measures with `captureElementImage`, allocates once with `texImage2D(…, null)` (again only
     *   when the size changes), then copies with `texElementSubImage2D`.
     * - 150–154: `texElementImage2D(target, internalformat, element)`.
     * - legacy: `texElementImage2D(target, level, internalformat, format, type, element)`.
     */
    export function uploadElementTexture(gl: WebGL2RenderingContext, target: ElementTexture, element: Element) {
      const g = gl as any;
      const support = getHtmlCanvasSupport();
      const box = element.getBoundingClientRect();
      const html = element as HTMLElement;
      // Layout size, unaffected by the CSS transform used for hit-testing.
      const width = html.offsetWidth || box.width;
      const height = html.offsetHeight || box.height;
      if (!width || !height) return false;
      gl.bindTexture(gl.TEXTURE_2D, target.texture);
      try {
        if (support.version === "155+" && typeof g.texElementSubImage2D === "function") {
          const canvas = gl.canvas as any;
          let natural = { width, height };
          if (typeof canvas.captureElementImage === "function") {
            const image = canvas.captureElementImage(element);
            natural = { width: image.width, height: image.height };
            image.close?.();
          }
          if (!target.allocated || target.allocated.width !== natural.width || target.allocated.height !== natural.height) {
            gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, natural.width, natural.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
            target.allocated = natural;
          }
          g.texElementSubImage2D(gl.TEXTURE_2D, 0, 0, 0, element);
        } else if (support.version === "legacy") {
          g.texElementImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, element);
        } else if (typeof g.texElementImage2D === "function") {
          g.texElementImage2D(gl.TEXTURE_2D, gl.RGBA8, element);
        } else {
          return false;
        }
      } catch {
        return false;
      }
      target.width = width;
      target.height = height;
      return true;
    }
    /* eslint-enable @typescript-eslint/no-explicit-any */
    lib/html-canvas/use-html-canvas.ts
    "use client";
    
    import { useCallback, useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore } from "react";
    import { useReducedMotion } from "motion/react";
    import { drawableCanvasAttributes, prepareDrawableCanvas, requestCanvasPaint } from "@/lib/html-canvas/setup";
    import { getHtmlCanvasSupport, NO_SUPPORT, supportsContext, type HtmlCanvasSupport } from "@/lib/html-canvas/support";
    
    export type HtmlCanvasMode = "auto" | "native" | "fallback";
    type ContextType = "2d" | "webgl2";
    type ContextFor<C extends ContextType> = C extends "2d" ? CanvasRenderingContext2D : WebGL2RenderingContext;
    
    export interface HtmlCanvasFrame<C extends ContextType> {
      ctx: ContextFor<C>;
      canvas: HTMLCanvasElement;
      /** Canvas size in CSS px. */
      width: number;
      height: number;
      /** Device pixels per CSS px used for the backing store (capped). */
      dpr: number;
      /** Seconds since the hook started. */
      time: number;
      /** Seconds since the previous render. */
      delta: number;
      /** Why this render happened: drawn elements repainted, the canvas resized, or an animation frame. */
      reason: "paint" | "resize" | "frame" | "request";
      /** Elements that repainted (from the paint event), when known. */
      changed: readonly Element[];
    }
    
    export interface UseHtmlCanvasOptions<C extends ContextType> {
      /** Context to draw with. */
      context: C;
      /** "auto" uses the API when available, "fallback" never does, "native" requires it. @default "auto" */
      mode?: HtmlCanvasMode;
      /** Run a render every frame while true (e.g. while a ripple is fading). Paused offscreen and in hidden tabs. */
      animating?: boolean;
      /** Called once per context (again after a lost context is restored). Return a cleanup. */
      setup?: (ctx: ContextFor<C>, canvas: HTMLCanvasElement) => void | (() => void);
      /** Draws a frame. Upload element textures only when `reason` is "paint" or "resize". */
      render: (frame: HtmlCanvasFrame<C>) => void;
      /** Highest device pixel ratio for the backing store. @default 2 */
      maxDpr?: number;
      /** Context attributes for WebGL. */
      contextAttributes?: WebGLContextAttributes;
    }
    
    export interface HtmlCanvasController {
      /** True when the canvas path is active; render the fallback DOM otherwise. */
      native: boolean;
      /** What the browser supports (none on the server and during hydration). */
      support: HtmlCanvasSupport;
      /** Ref for the <canvas>. */
      canvasRef: (canvas: HTMLCanvasElement | null) => void;
      /** Spread onto the <canvas> so it lays out and paints its children from the first layout. */
      canvasProps: Record<string, string>;
      /** Asks for one more render (and a browser paint event where supported). */
      invalidate: () => void;
    }
    
    const noop = () => () => {};
    
    /**
     * Ties the HTML-in-Canvas adapter together: decides native vs. fallback (never during SSR or
     * hydration, never under reduced motion), prepares the canvas, renders on the canvas `paint` event
     * and on resize, runs a frame loop only while `animating`, pauses offscreen and in hidden tabs,
     * recovers from a lost WebGL context and cleans up on unmount.
     */
    export function useHtmlCanvas<C extends ContextType>({
      context,
      mode = "auto",
      animating = false,
      setup,
      render,
      maxDpr = 2,
      contextAttributes,
    }: UseHtmlCanvasOptions<C>): HtmlCanvasController {
      const hydrated = useSyncExternalStore(
        noop,
        () => true,
        () => false,
      );
      const reduceMotion = useReducedMotion();
      const support = hydrated ? getHtmlCanvasSupport() : NO_SUPPORT;
      const [failed, setFailed] = useState(false);
      const native = hydrated && !failed && mode !== "fallback" && !reduceMotion && supportsContext(support, context);
    
      // The element lives in a ref (it is mutated: size, attributes); the counter re-runs the effect when it changes.
      const canvasEl = useRef<HTMLCanvasElement | null>(null);
      const [canvasVersion, setCanvasVersion] = useState(0);
      const canvasRef = useCallback((el: HTMLCanvasElement | null) => {
        if (canvasEl.current === el) return;
        canvasEl.current = el;
        setCanvasVersion((v) => v + 1);
      }, []);
      const renderRef = useRef(render);
      const setupRef = useRef(setup);
      const animatingRef = useRef(animating);
      useLayoutEffect(() => {
        renderRef.current = render;
        setupRef.current = setup;
        animatingRef.current = animating;
      });
      const kick = useRef<(reason: HtmlCanvasFrame<C>["reason"]) => void>(() => {});
    
      useEffect(() => {
        const canvas = canvasEl.current;
        if (!native || !canvas) return;
        prepareDrawableCanvas(canvas);
        const ctx = canvas.getContext(context, context === "webgl2" ? { alpha: true, premultipliedAlpha: true, antialias: true, ...contextAttributes } : undefined) as ContextFor<C> | null;
        if (!ctx) {
          // Defer so the state change happens outside the effect body.
          const t = window.setTimeout(() => setFailed(true), 0);
          return () => window.clearTimeout(t);
        }
        let cleanupSetup: void | (() => void);
        let ready = false;
        const runSetup = () => {
          try {
            cleanupSetup = setupRef.current?.(ctx, canvas);
            ready = true;
          } catch (error) {
            console.error(error);
            ready = false;
            window.setTimeout(() => setFailed(true), 0);
          }
        };
        runSetup();
    
        const start = performance.now();
        // Frame time is measured between loop frames only, so the first frame after idling has a normal step.
        let lastFrame = 0;
        let size = { width: 0, height: 0, dpr: 1 };
        let visible = true;
        let frame = 0;
        let changed: readonly Element[] = [];
    
        const draw = (reason: HtmlCanvasFrame<C>["reason"]) => {
          if (!ready || !size.width || !size.height) return;
          const now = performance.now();
          const delta = reason === "frame" && lastFrame ? Math.min(1 / 20, (now - lastFrame) / 1000) : reason === "frame" ? 1 / 60 : 0;
          if (reason === "frame") lastFrame = now;
          try {
            renderRef.current({ ctx, canvas, width: size.width, height: size.height, dpr: size.dpr, time: (now - start) / 1000, delta, reason, changed });
          } catch (error) {
            console.error(error);
          }
          changed = [];
        };
    
        const loop = () => {
          frame = 0;
          if (!visible || document.hidden || !animatingRef.current) {
            lastFrame = 0;
            return;
          }
          draw("frame");
          frame = requestAnimationFrame(loop);
        };
        const ensureLoop = () => {
          if (!frame && visible && !document.hidden && animatingRef.current) frame = requestAnimationFrame(loop);
        };
        kick.current = (reason) => {
          draw(reason);
          ensureLoop();
        };
    
        const resize = () => {
          const rect = canvas.getBoundingClientRect();
          const dpr = Math.min(maxDpr, window.devicePixelRatio || 1);
          const width = Math.max(1, Math.round(rect.width));
          const height = Math.max(1, Math.round(rect.height));
          if (width === size.width && height === size.height && dpr === size.dpr) return;
          size = { width, height, dpr };
          canvas.width = Math.round(width * dpr);
          canvas.height = Math.round(height * dpr);
          draw("resize");
          requestCanvasPaint(canvas);
        };
        const resizeObserver = new ResizeObserver(resize);
        resizeObserver.observe(canvas);
        resize();
    
        const onPaint = (event: Event) => {
          changed = ((event as Event & { changedElements?: Element[] }).changedElements ?? []) as Element[];
          draw("paint");
          ensureLoop();
        };
        canvas.addEventListener("paint", onPaint);
    
        const io = new IntersectionObserver(([entry]) => {
          visible = entry?.isIntersecting ?? true;
          ensureLoop();
        });
        io.observe(canvas);
        const onVisibility = () => ensureLoop();
        document.addEventListener("visibilitychange", onVisibility);
    
        const onLost = (event: Event) => {
          event.preventDefault();
          ready = false;
          cancelAnimationFrame(frame);
          frame = 0;
        };
        const onRestored = () => {
          runSetup();
          draw("resize");
          requestCanvasPaint(canvas);
        };
        canvas.addEventListener("webglcontextlost", onLost);
        canvas.addEventListener("webglcontextrestored", onRestored);
    
        requestCanvasPaint(canvas);
    
        return () => {
          cancelAnimationFrame(frame);
          resizeObserver.disconnect();
          io.disconnect();
          canvas.removeEventListener("paint", onPaint);
          canvas.removeEventListener("webglcontextlost", onLost);
          canvas.removeEventListener("webglcontextrestored", onRestored);
          document.removeEventListener("visibilitychange", onVisibility);
          kick.current = () => {};
          if (typeof cleanupSetup === "function") cleanupSetup();
        };
        // contextAttributes and maxDpr are read once per canvas.
        // eslint-disable-next-line react-hooks/exhaustive-deps
      }, [native, canvasVersion, context]);
    
      // Start or stop the loop when `animating` flips.
      useEffect(() => {
        if (animating) kick.current("frame");
      }, [animating]);
    
      const invalidate = useCallback(() => {
        kick.current("request");
        if (canvasEl.current) requestCanvasPaint(canvasEl.current);
      }, []);
    
      return { native, support, canvasRef, canvasProps: drawableCanvasAttributes(support), invalidate };
    }
  3. Copy the source

    components/ui/peel-card/peel-card.tsx
    "use client";
    
    import { useEffect, useId, useRef, useState, type ReactNode } from "react";
    import { motion, useReducedMotion } from "motion/react";
    import { cn } from "@/lib/utils";
    import { createGrid, createProgram, drawMesh, PROJECT_GLSL, rgb, type Mesh, type Program } from "@/lib/html-canvas/gl";
    import { createElementTexture, uploadElementTexture, type ElementTexture } from "@/lib/html-canvas/texture-webgl";
    import { syncElementGeometry } from "@/lib/html-canvas/sync-geometry";
    import { useHtmlCanvas, type HtmlCanvasMode } from "@/lib/html-canvas/use-html-canvas";
    
    export interface PeelCardProps {
      /** The face on top. */
      front: ReactNode;
      /** The face revealed underneath. */
      back: ReactNode;
      /** Revealed state (controlled). */
      revealed?: boolean;
      /** Starting state when uncontrolled. @default false */
      defaultRevealed?: boolean;
      /** Called when the card is peeled off or covered again. */
      onRevealChange?: (revealed: boolean) => void;
      /** Color of the paper's underside. @default "#f4f1ea" */
      paperColor?: string;
      /** Accessible names for the corner control. */
      labels?: { reveal?: string; cover?: string };
      /** "auto" uses HTML-in-Canvas when available, "fallback" never does. @default "auto" */
      rendering?: HtmlCanvasMode;
      /** Called when the rendering mode is known. */
      onModeChange?: (native: boolean) => void;
      /** Classes for the root. */
      className?: string;
    }
    
    /** Room around the card for the flap to swing into, in px. */
    const PAD = 48;
    const RADIUS = 18;
    const HINT = 22;
    
    const FRONT_VERT = /* glsl */ `#version 300 es
    in vec2 a_pos;
    uniform vec2 u_size;
    uniform vec2 u_offset;
    uniform vec2 u_corner;
    uniform vec2 u_point;
    uniform float u_radius;
    out vec2 v_uv;
    out float v_angle;
    ${PROJECT_GLSL}
    void main() {
      vec2 x = a_pos * u_size;
      vec3 pos = vec3(x, 0.0);
      float angle = 0.0;
      vec2 cp = u_point - u_corner;
      float len = length(cp);
      if (len > 0.5) {
        // Fold line: the perpendicular bisector of corner → pointer, shifted so the flap lands on the pointer.
        vec2 n = -cp / len;
        float pi = 3.14159265;
        vec2 m = (u_corner + u_point) * 0.5 - n * pi * u_radius * 0.5;
        float s = dot(x - m, n);
        if (s > 0.0) {
          float r = u_radius;
          float s2;
          float z;
          if (s < pi * r) {
            angle = s / r;
            s2 = r * sin(angle);
            z = r * (1.0 - cos(angle));
          } else {
            angle = pi;
            s2 = -(s - pi * r);
            z = 2.0 * r;
          }
          pos = vec3(x - n * s + n * s2, z);
        }
      }
      v_uv = a_pos;
      v_angle = angle;
      vec4 clip = projectCss(vec4(u_offset + pos.xy, 0.0, 1.0));
      clip.z = (0.4 - pos.z * 0.004) * clip.w;
      gl_Position = clip;
    }`;
    
    const FRONT_FRAG = /* glsl */ `#version 300 es
    precision highp float;
    in vec2 v_uv;
    in float v_angle;
    uniform sampler2D u_tex;
    uniform vec3 u_paper;
    uniform float u_alpha;
    out vec4 outColor;
    void main() {
      vec4 c = texture(u_tex, v_uv);
      if (c.a < 0.01) discard;
      if (v_angle > 1.5708) {
        // The flap shows the paper's underside, lit by how far it has turned.
        float light = 0.82 + 0.18 * -cos(v_angle);
        outColor = vec4(u_paper * light, 1.0) * c.a * u_alpha;
      } else {
        float light = 1.0 - sin(v_angle) * 0.18;
        outColor = vec4(c.rgb * light, c.a) * u_alpha;
      }
    }`;
    
    const BACK_VERT = /* glsl */ `#version 300 es
    in vec2 a_pos;
    uniform vec2 u_size;
    uniform vec2 u_offset;
    out vec2 v_px;
    out vec2 v_uv;
    ${PROJECT_GLSL}
    void main() {
      v_uv = a_pos;
      v_px = a_pos * u_size;
      vec4 clip = projectCss(vec4(u_offset + v_px, 0.0, 1.0));
      clip.z = 0.9 * clip.w;
      gl_Position = clip;
    }`;
    
    const BACK_FRAG = /* glsl */ `#version 300 es
    precision highp float;
    in vec2 v_px;
    in vec2 v_uv;
    uniform sampler2D u_tex;
    uniform vec2 u_corner;
    uniform vec2 u_point;
    uniform float u_radius;
    out vec4 outColor;
    void main() {
      vec4 c = texture(u_tex, v_uv);
      vec2 cp = u_point - u_corner;
      float len = length(cp);
      if (len > 0.5) {
        // A soft shadow cast by the curl onto the face below, strongest along the fold.
        vec2 n = -cp / len;
        vec2 m = (u_corner + u_point) * 0.5 - n * 3.14159265 * u_radius * 0.5;
        float s = dot(v_px - m, n);
        float shadow = s > 0.0 ? exp(-s / (u_radius * 1.6)) * 0.35 : 0.0;
        c.rgb *= 1.0 - shadow;
      }
      outColor = c;
    }`;
    
    /**
     * A DOM card (a coupon, a profile, real links) that peels like paper through HTML-in-Canvas: drag the
     * lifted corner to curl it back and reveal a second live face underneath. Released past halfway it
     * peels off; otherwise it springs back. Without the API, the corner button flips the card in CSS 3D.
     */
    export function PeelCard({
      front,
      back,
      revealed: revealedProp,
      defaultRevealed = false,
      onRevealChange,
      paperColor = "#f4f1ea",
      labels,
      rendering = "auto",
      onModeChange,
      className,
    }: PeelCardProps) {
      const id = useId();
      const reduceMotion = useReducedMotion();
      const [inner, setInner] = useState(defaultRevealed);
      const revealed = revealedProp ?? inner;
      const rootRef = useRef<HTMLDivElement>(null);
      const frontRef = useRef<HTMLDivElement>(null);
      const backRef = useRef<HTMLDivElement>(null);
      const [size, setSize] = useState<{ w: number; h: number } | null>(null);
      const [animating, setAnimating] = useState(false);
      const peel = useRef({ x: 0, y: 0, tx: 0, ty: 0, dragging: false, ready: false, startX: 0, startY: 0, moved: false });
      const gl = useRef<{ front: Program; back: Program; mesh: Mesh; quad: Mesh; tf: ElementTexture; tb: ElementTexture } | null>(null);
    
      const setRevealed = (next: boolean) => {
        if (revealedProp === undefined) setInner(next);
        onRevealChange?.(next);
      };
    
      const { native, canvasRef, canvasProps, invalidate } = useHtmlCanvas({
        context: "webgl2",
        mode: rendering,
        animating,
        contextAttributes: { depth: true },
        setup: (ctx) => {
          gl.current = {
            front: createProgram(ctx, FRONT_VERT, FRONT_FRAG),
            back: createProgram(ctx, BACK_VERT, BACK_FRAG),
            mesh: createGrid(ctx, 28, 28),
            quad: createGrid(ctx),
            tf: createElementTexture(ctx),
            tb: createElementTexture(ctx),
          };
          return () => {
            const g = gl.current;
            if (!g) return;
            ctx.deleteProgram(g.front.program);
            ctx.deleteProgram(g.back.program);
            ctx.deleteTexture(g.tf.texture);
            ctx.deleteTexture(g.tb.texture);
            gl.current = null;
          };
        },
        render: ({ ctx, canvas, width, height: h, reason, delta }) => {
          const g = gl.current;
          const f = frontRef.current;
          const b = backRef.current;
          if (!g || !f || !b) return;
          if (reason !== "frame" || !g.tf.width) {
            uploadElementTexture(ctx, g.tf, f);
            uploadElementTexture(ctx, g.tb, b);
            const at = new DOMMatrix().translate(PAD, PAD);
            syncElementGeometry(canvas, f, at);
            syncElementGeometry(canvas, b, at);
          }
          const w = g.tf.width || f.offsetWidth;
          const hh = g.tf.height || f.offsetHeight;
          const corner = { x: w, y: hh };
          const p = peel.current;
          if (!p.ready) {
            p.x = p.tx = corner.x - HINT;
            p.y = p.ty = corner.y - HINT;
            p.ready = true;
          }
          // Ease toward the target (the pointer while dragging).
          const k = p.dragging ? 1 - Math.exp(-delta * 30) : 1 - Math.exp(-delta * 9);
          p.x += (p.tx - p.x) * (reason === "frame" ? k : 0);
          p.y += (p.ty - p.y) * (reason === "frame" ? k : 0);
          const settled = Math.hypot(p.tx - p.x, p.ty - p.y) < 0.5;
          if (settled) {
            p.x = p.tx;
            p.y = p.ty;
            if (!p.dragging && animating) window.setTimeout(() => setAnimating(false), 0);
          }
    
          ctx.viewport(0, 0, canvas.width, canvas.height);
          ctx.clearColor(0, 0, 0, 0);
          ctx.clearDepth(1);
          ctx.clear(ctx.COLOR_BUFFER_BIT | ctx.DEPTH_BUFFER_BIT);
          ctx.enable(ctx.DEPTH_TEST);
          ctx.depthFunc(ctx.LEQUAL);
          ctx.enable(ctx.BLEND);
          ctx.blendFunc(ctx.ONE, ctx.ONE_MINUS_SRC_ALPHA);
          ctx.activeTexture(ctx.TEXTURE0);
    
          ctx.useProgram(g.back.program);
          ctx.uniform2f(g.back.u("u_canvas"), width, h);
          ctx.uniform2f(g.back.u("u_size"), g.tb.width || w, g.tb.height || hh);
          ctx.uniform2f(g.back.u("u_offset"), PAD, PAD);
          ctx.uniform2f(g.back.u("u_corner"), corner.x, corner.y);
          ctx.uniform2f(g.back.u("u_point"), p.x, p.y);
          ctx.uniform1f(g.back.u("u_radius"), RADIUS);
          ctx.bindTexture(ctx.TEXTURE_2D, g.tb.texture);
          ctx.uniform1i(g.back.u("u_tex"), 0);
          drawMesh(ctx, g.quad);
    
          const gone = revealed && settled;
          if (!gone) {
            ctx.useProgram(g.front.program);
            ctx.uniform2f(g.front.u("u_canvas"), width, h);
            ctx.uniform2f(g.front.u("u_size"), w, hh);
            ctx.uniform2f(g.front.u("u_offset"), PAD, PAD);
            ctx.uniform2f(g.front.u("u_corner"), corner.x, corner.y);
            ctx.uniform2f(g.front.u("u_point"), p.x, p.y);
            ctx.uniform1f(g.front.u("u_radius"), RADIUS);
            ctx.uniform3f(g.front.u("u_paper"), ...rgb(paperColor));
            ctx.uniform1f(g.front.u("u_alpha"), 1);
            ctx.bindTexture(ctx.TEXTURE_2D, g.tf.texture);
            ctx.uniform1i(g.front.u("u_tex"), 0);
            drawMesh(ctx, g.mesh);
          }
          ctx.disable(ctx.DEPTH_TEST);
        },
      });
    
      useEffect(() => onModeChange?.(native), [native, onModeChange]);
    
      // The canvas wraps the taller face.
      useEffect(() => {
        if (!native) return;
        // Canvas children shrink to fit, so the faces take the root's width explicitly.
        const measure = () => {
          const f = frontRef.current;
          const b = backRef.current;
          const root = rootRef.current;
          if (f && b && root) setSize({ w: root.clientWidth, h: Math.max(f.offsetHeight, b.offsetHeight) });
        };
        const observer = new ResizeObserver(measure);
        if (rootRef.current) observer.observe(rootRef.current);
        if (frontRef.current) observer.observe(frontRef.current);
        if (backRef.current) observer.observe(backRef.current);
        measure();
        return () => observer.disconnect();
      }, [native]);
    
      // Revealed: the flap swings past the opposite corner. Covered: it rests on the corner with a small lift.
      const aim = (next: boolean) => {
        const f = frontRef.current;
        if (!f) return;
        const w = f.offsetWidth;
        const h = f.offsetHeight;
        const p = peel.current;
        p.tx = next ? w - 2.3 * w : w - HINT;
        p.ty = next ? h - 2.3 * h : h - HINT;
        setAnimating(true);
        invalidate();
      };
    
      useEffect(() => {
        if (native) aim(revealed);
        // aim reads refs only.
        // eslint-disable-next-line react-hooks/exhaustive-deps
      }, [revealed, native]);
    
      const local = (event: React.PointerEvent) => {
        const rect = frontRef.current?.getBoundingClientRect();
        const f = frontRef.current;
        if (!rect || !f) return { x: 0, y: 0 };
        // The front's box is synced to the card; its layout size is unscaled.
        return { x: ((event.clientX - rect.left) / rect.width) * f.offsetWidth, y: ((event.clientY - rect.top) / rect.height) * f.offsetHeight };
      };
    
      const onPointerDown = (event: React.PointerEvent<HTMLButtonElement>) => {
        // Peeling is a drag on the front; covering again is a click.
        if (!native || revealed) return;
        const p = peel.current;
        p.dragging = true;
        p.moved = false;
        p.startX = event.clientX;
        p.startY = event.clientY;
        event.currentTarget.setPointerCapture(event.pointerId);
      };
      const onPointerMove = (event: React.PointerEvent<HTMLButtonElement>) => {
        const p = peel.current;
        if (!p.dragging) return;
        if (Math.hypot(event.clientX - p.startX, event.clientY - p.startY) > 4) p.moved = true;
        if (!p.moved) return;
        const q = local(event);
        p.tx = q.x;
        p.ty = q.y;
        setAnimating(true);
      };
      const onPointerUp = (event: React.PointerEvent<HTMLButtonElement>) => {
        const p = peel.current;
        if (!p.dragging) return;
        p.dragging = false;
        if (!p.moved) return;
        event.preventDefault();
        const f = frontRef.current;
        if (!f) return;
        // Past halfway along the diagonal it peels off; otherwise it springs back.
        const w = f.offsetWidth;
        const h = f.offsetHeight;
        const travelled = Math.hypot(w - p.tx, h - p.ty) / Math.hypot(w, h);
        if (travelled > 0.5) setRevealed(true);
        else aim(false);
      };
      const onClick = () => {
        if (peel.current.moved) {
          peel.current.moved = false;
          return;
        }
        setRevealed(!revealed);
      };
    
      const corner = (
        <button
          type="button"
          aria-label={revealed ? (labels?.cover ?? "Cover the back again") : (labels?.reveal ?? "Peel to reveal the back")}
          aria-controls={`${id}-faces`}
          aria-expanded={revealed}
          onPointerDown={onPointerDown}
          onPointerMove={onPointerMove}
          onPointerUp={onPointerUp}
          onPointerCancel={() => (peel.current.dragging = false)}
          onClick={onClick}
          className={cn(
            "absolute z-10 size-12 cursor-grab touch-none rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring active:cursor-grabbing",
            native ? (revealed ? "top-1 right-1" : "right-0 bottom-0") : "right-1 bottom-1 grid place-items-center bg-background/80 shadow-sm",
          )}
        >
          {!native ? (
            <svg viewBox="0 0 16 16" className="size-4 text-foreground" aria-hidden="true">
              <path d="M3 13L13 3M13 3H7M13 3v6" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
          ) : null}
        </button>
      );
    
      if (!native) {
        return (
          <div className={cn("relative w-full max-w-sm [perspective:1200px]", className)}>
            <motion.div
              id={`${id}-faces`}
              className="relative grid [transform-style:preserve-3d] [&>*]:[grid-area:1/1]"
              initial={false}
              animate={{ rotateY: revealed ? 180 : 0 }}
              transition={reduceMotion ? { duration: 0 } : { type: "spring", stiffness: 180, damping: 22 }}
            >
              <div className="[backface-visibility:hidden]" aria-hidden={revealed} inert={revealed}>
                {front}
              </div>
              <div className="[transform:rotateY(180deg)] [backface-visibility:hidden]" aria-hidden={!revealed} inert={!revealed}>
                {back}
              </div>
            </motion.div>
            {corner}
          </div>
        );
      }
    
      return (
        <div ref={rootRef} className={cn("relative w-full max-w-sm", className)} style={{ height: size?.h }}>
          <div className="absolute" style={{ inset: -PAD }}>
            <canvas ref={canvasRef} {...canvasProps} id={`${id}-faces`} className="pointer-events-none block size-full">
              <div ref={backRef} className="pointer-events-auto" style={{ width: size?.w ?? 320 }} aria-hidden={!revealed} inert={!revealed}>
                {back}
              </div>
              <div ref={frontRef} className="pointer-events-auto" style={{ width: size?.w ?? 320 }} aria-hidden={revealed} inert={revealed}>
                {front}
              </div>
            </canvas>
          </div>
          {corner}
        </div>
      );
    }

Usage

import { PeelCard } from "@/components/ui/peel-card/peel-card";

<PeelCard
  front={<Coupon />}
  back={<CouponCode />}
  onRevealChange={(revealed) => revealed && track("coupon_revealed")}
/>

API reference

PropTypeDefaultDescription
front*ReactNode–The face on top.
back*ReactNode–The face revealed underneath.
revealedboolean–Revealed state (controlled).
defaultRevealedbooleanfalseStarting state when uncontrolled.
onRevealChange(revealed: boolean) => void–Called when the card is peeled off or covered again.
paperColorstring"#f4f1ea"Color of the paper's underside.
labels{ reveal?: string; cover?: string }–Accessible names for the corner control.
renderingHtmlCanvasMode"auto""auto" uses HTML-in-Canvas when available, "fallback" never does.
onModeChange(native: boolean) => void–Called when the rendering mode is known.
classNamestring–Classes for the root.
  • Experimental: uses the HTML-in-Canvas origin trial through src/lib/html-canvas/. Works in every browser via the fallback.
  • The curl is a 28 × 28 grid wrapped around a cylinder in the vertex shader, with the paper's underside on the flap and a soft shadow along the fold on the face below.
  • Released past halfway along the diagonal, the front peels off; otherwise it springs back to its lifted corner.

Accessibility

  • Both faces are live DOM; only the visible one is interactive and in the accessibility tree (the other is inert and aria-hidden).
  • The corner is a button named "Peel to reveal the back" or "Cover the back again" with aria-expanded, so the card works from the keyboard: press it instead of dragging.
  • With reduced motion, or without the HTML-in-Canvas API, the corner button flips the card in CSS 3D (instantly under reduced motion).