HTML in Canvasv0.3.0
Dissolve Transition
Outgoing content dissolves into pixels as the next resolves.
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/dissolve-transition.jsonManual
Install the dependencies
npm install clsx motion tailwind-mergeAdd the shared helpers
Components use
cn()fromlib/utils.tsand the motion tokens below. See Installation if you have not set them up yet.lib/color.tsexport type Vec3 = [r: number, g: number, b: number]; /** * Parses #rgb, #rrggbb or #rrggbbaa (alpha is ignored) into 0–255 channels. * Anything else falls back to black, so a typo never crashes a shader. */ export function hexToRgb(hex: string): Vec3 { let value = hex.trim().replace(/^#/, ""); if (value.length === 3 || value.length === 4) value = [...value.slice(0, 3)].map((c) => c + c).join(""); if (!/^[\da-f]{6}([\da-f]{2})?$/i.test(value)) return [0, 0, 0]; const n = Number.parseInt(value.slice(0, 6), 16); return [(n >> 16) & 255, (n >> 8) & 255, n & 255]; } /** Hex color as a normalized vec3 (each channel 0–1) for shader uniforms. */ export function hexToVec3(hex: string): Vec3 { const [r, g, b] = hexToRgb(hex); return [r / 255, g / 255, b / 255]; } /** * Any CSS color the browser understands (hex, rgb(), oklch(), color-mix() or a variable such as * `var(--primary)`) as 0–255 channels, computed in the context of `element` so theme variables * resolve. Hex takes a fast path; everything else is computed once per call, so cache the result * instead of calling this every frame. Browser only; unreadable values fall back to black. */ export function cssColorToRgb(color: string, element: Element): Vec3 { const value = color.trim(); if (/^#[\da-f]{3,8}$/i.test(value)) return hexToRgb(value); // Children of a canvas still get computed styles, but a regular parent is the safer host. const host = element instanceof HTMLCanvasElement ? (element.parentElement ?? document.body) : element; const probe = document.createElement("span"); probe.style.cssText = "position:absolute;width:0;height:0;overflow:hidden;visibility:hidden"; probe.style.color = value; host.appendChild(probe); const computed = getComputedStyle(probe).color; probe.remove(); // A 1×1 canvas turns any computed color space (oklch, color(srgb …)) into sRGB bytes. const ctx = document.createElement("canvas").getContext("2d", { willReadFrequently: true }); if (!ctx) return [0, 0, 0]; ctx.fillStyle = "#000"; ctx.fillStyle = computed; ctx.fillRect(0, 0, 1, 1); const [r, g, b] = ctx.getImageData(0, 0, 1, 1).data; return [r, g, b]; } /** * Calls `onChange` when the page theme may have changed: a class or data-theme change on <html> or * <body> (shadcn's `.dark`, next-themes, a data-theme switch) or a change of the OS color scheme. * Resolved colors are cached, so re-resolve them here. Browser only; returns the unsubscribe. */ export function observeTheme(onChange: () => void): () => void { const observer = new MutationObserver(onChange); const options = { attributes: true, attributeFilter: ["class", "data-theme"] }; observer.observe(document.documentElement, options); if (document.body) observer.observe(document.body, options); const scheme = window.matchMedia("(prefers-color-scheme: dark)"); scheme.addEventListener("change", onChange); return () => { observer.disconnect(); scheme.removeEventListener("change", onChange); }; } /** `cssColorToRgb` as a normalized vec3 (each channel 0–1) for shader uniforms. */ export function cssColorToVec3(color: string, element: Element): Vec3 { const [r, g, b] = cssColorToRgb(color, element); return [r / 255, g / 255, b / 255]; } const toLinear = (c: number) => (c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4); const toGamma = (c: number) => (c <= 0.0031308 ? 12.92 * c : 1.055 * c ** (1 / 2.4) - 0.055); /** 0–255 sRGB to OKLCH: lightness 0–1, chroma, hue in radians. */ export function rgbToOklch([r, g, b]: Vec3): Vec3 { const [lr, lg, lb] = [r, g, b].map((v) => toLinear(v / 255)); const l = Math.cbrt(0.4122214708 * lr + 0.5363325363 * lg + 0.0514459929 * lb); const m = Math.cbrt(0.2119034982 * lr + 0.6806995451 * lg + 0.1073969566 * lb); const s = Math.cbrt(0.0883024619 * lr + 0.2817188376 * lg + 0.6299787005 * lb); const L = 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s; const A = 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s; const B = 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s; return [L, Math.hypot(A, B), Math.atan2(B, A)]; } /** OKLCH back to 0–255 sRGB, clamped into gamut. */ export function oklchToRgb([L, C, h]: Vec3): Vec3 { const A = C * Math.cos(h); const B = C * Math.sin(h); const l = (L + 0.3963377774 * A + 0.2158037573 * B) ** 3; const m = (L - 0.1055613458 * A - 0.0638541728 * B) ** 3; const s = (L - 0.0894841775 * A - 1.291485548 * B) ** 3; const rgb = [4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s, -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s, -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s]; return rgb.map((v) => Math.round(Math.min(1, Math.max(0, toGamma(Math.min(1, Math.max(0, v))))) * 255)) as Vec3; } /** * Mixes two 0–255 colors in OKLCH, taking the short way around the hue circle, so midpoints keep * their chroma instead of turning muddy the way an RGB mix does. */ export function mixOklch(a: Vec3, b: Vec3, t: number): Vec3 { const [L1, C1, h1] = rgbToOklch(a); const [L2, C2, h2] = rgbToOklch(b); // A near-gray end has no meaningful hue: borrow the other end's. const ha = C1 < 0.02 ? h2 : h1; const hb = C2 < 0.02 ? h1 : h2; let dh = hb - ha; if (dh > Math.PI) dh -= Math.PI * 2; if (dh < -Math.PI) dh += Math.PI * 2; return oklchToRgb([L1 + (L2 - L1) * t, C1 + (C2 - C1) * t, ha + dh * t]); }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.tsimport 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.tsimport { 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.tsimport { 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 }; }lib/motion.tsimport type { Transition, Variants } from "motion/react"; /** Durations in seconds. */ export const duration = { instant: 0.1, quick: 0.18, base: 0.28, slow: 0.45, } as const; /** Cubic-bezier curves. */ export const ease = { /** Entering, UI response. */ out: [0.22, 1, 0.36, 1], /** Moving on screen. */ inOut: [0.65, 0, 0.35, 1], /** Sheets and the mobile menu. */ drawer: [0.32, 0.72, 0, 1], } as const; /** Everyday UI: presses, icon swaps, popovers and modals. Exits run at `exitFactor` of the enter. */ export const ui = { press: { scale: 0.96, duration: 0.12 }, icon: { type: "spring", duration: 0.3, bounce: 0 }, popover: { duration: 0.18, ease: ease.out }, modal: { duration: 0.24, ease: ease.out }, exitFactor: 0.6, } as const; /** Once-per-visit motion on the landing page: hero letters, the reel and the afterimage. */ export const kinetic = { heroLetter: { duration: 0.6, ease: ease.out }, /** Delay per letter, eased so the wave slows toward the end. */ heroStep: 0.035, reelSwap: { type: "spring", duration: 0.5, bounce: 0.1 }, /** Two afterimages: lag in seconds and opacity of each. */ ghost: { lag: [0.04, 0.09], opacity: [0.14, 0.06] }, } as const; /** Spring presets. */ export const spring = { snappy: { type: "spring", stiffness: 500, damping: 30 }, smooth: { type: "spring", stiffness: 260, damping: 26 }, bouncy: { type: "spring", stiffness: 300, damping: 15 }, } as const satisfies Record<string, Transition>; /** Stagger between siblings, in seconds (0.03–0.06). */ export const stagger = { tight: 0.03, base: 0.045, loose: 0.06, } as const; /** Blur + fade + y-offset. Falls back to a plain fade under reduced motion. */ export function enterVariants(reduceMotion?: boolean | null, y = 8): Variants { if (reduceMotion) { return { hidden: { opacity: 0 }, visible: { opacity: 1, transition: { duration: duration.base } }, exit: { opacity: 0, transition: { duration: duration.quick } }, }; } return { hidden: { opacity: 0, y, filter: "blur(4px)" }, visible: { opacity: 1, y: 0, filter: "blur(0px)", transition: { duration: duration.base, ease: ease.out }, }, exit: { opacity: 0, y: -y / 2, filter: "blur(4px)", transition: { duration: duration.quick, ease: ease.out }, }, }; } /** Scale 0.96 → 1 for popovers, menus and dialogs. */ export function overlayVariants(reduceMotion?: boolean | null): Variants { if (reduceMotion) { return { hidden: { opacity: 0 }, visible: { opacity: 1, transition: { duration: duration.quick } }, exit: { opacity: 0, transition: { duration: duration.instant } }, }; } return { hidden: { opacity: 0, scale: 0.96, filter: "blur(2px)" }, visible: { opacity: 1, scale: 1, filter: "blur(0px)", transition: { duration: duration.quick, ease: ease.out }, }, exit: { opacity: 0, scale: 0.96, filter: "blur(2px)", transition: { duration: duration.instant + 0.02, ease: ease.out }, }, }; } /** Parent variants that stagger their children in. */ export function staggerVariants(gap: number = stagger.base, delayChildren = 0): Variants { return { hidden: {}, visible: { transition: { staggerChildren: gap, delayChildren } }, exit: { transition: { staggerChildren: gap / 2, staggerDirection: -1 } }, }; }Copy the source
components/ui/dissolve-transition/dissolve-transition.tsx"use client"; import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react"; import { AnimatePresence, motion, useReducedMotion } from "motion/react"; import { cn } from "@/lib/utils"; import { ease } from "@/lib/motion"; import { cssColorToVec3, observeTheme, type Vec3 } from "@/lib/color"; import { createGrid, createProgram, drawMesh, PROJECT_GLSL, 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 DissolveTransitionProps { /** Identifies the current content. Changing it dissolves the old content into the new. */ contentKey: string | number; /** The current content. */ children: ReactNode; /** How content breaks up: growing pixel blocks, an ordered dither or a noise field. @default "pixel" */ mode?: "pixel" | "dither" | "noise"; /** Seconds the swap takes. @default 0.9 */ duration?: number; /** Where the dissolve starts sweeping from; "none" dissolves everywhere at once. @default "none" */ direction?: "none" | "up" | "down" | "left" | "right"; /** Color of the glowing edge in noise mode. @default "var(--primary)" */ edgeColor?: 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; /** Called when a transition finishes. */ onTransitionEnd?: () => void; /** Classes for the root. */ className?: string; } const VERT = /* glsl */ `#version 300 es in vec2 a_pos; uniform vec2 u_size; out vec2 v_uv; ${PROJECT_GLSL} void main() { v_uv = a_pos; gl_Position = projectCss(vec4(a_pos * u_size, 0.0, 1.0)); }`; const FRAG = /* glsl */ `#version 300 es precision highp float; in vec2 v_uv; uniform sampler2D u_out; uniform sampler2D u_in; uniform vec2 u_outSize; uniform vec2 u_inSize; uniform vec2 u_size; uniform float u_p; uniform int u_mode; uniform vec2 u_dir; uniform vec3 u_edge; out vec4 outColor; float hash(vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); } float vnoise(vec2 p) { vec2 i = floor(p), f = fract(p); vec2 u = f * f * (3.0 - 2.0 * f); return mix(mix(hash(i), hash(i + vec2(1, 0)), u.x), mix(hash(i + vec2(0, 1)), hash(i + vec2(1, 1)), u.x), u.y); } float bayer(vec2 p) { ivec2 c = ivec2(mod(p, 4.0)); int m[16] = int[16](0, 8, 2, 10, 12, 4, 14, 6, 3, 11, 1, 9, 15, 7, 13, 5); return (float(m[c.y * 4 + c.x]) + 0.5) / 16.0; } vec4 sampleIn(sampler2D t, vec2 px, vec2 size) { vec2 uv = px / size; if (uv.x < 0.0 || uv.y < 0.0 || uv.x > 1.0 || uv.y > 1.0) return vec4(0.0); return texture(t, uv); } void main() { vec2 px = v_uv * u_size; // A sweep coordinate (0 at the start edge, 1 at the far edge) biases each cell's threshold. float sweep = dot(u_dir, u_dir) > 0.0 ? clamp(dot(v_uv - 0.5, u_dir) + 0.5, 0.0, 1.0) : 0.5; float bias = dot(u_dir, u_dir) > 0.0 ? 0.55 : 0.0; float p = u_p * (1.0 + bias) - bias * 0.5; vec4 o; vec4 n; float tOut; float tIn; float edge = 0.0; if (u_mode == 0) { // Pixel: outgoing blocks grow and drop out; incoming blocks start coarse and sharpen. float bo = 1.0 + floor(u_p * 22.0); float bi = 1.0 + floor((1.0 - u_p) * 22.0); vec2 co = (floor(px / bo) + 0.5) * bo; vec2 ci = (floor(px / bi) + 0.5) * bi; o = sampleIn(u_out, co, u_outSize); n = sampleIn(u_in, ci, u_inSize); float h = hash(floor(px / 12.0)); tOut = mix(h, sweep, bias); tIn = tOut; } else if (u_mode == 1) { // Dither: an ordered Bayer threshold on 3px cells. vec2 cell = floor(px / 3.0); o = sampleIn(u_out, (cell + 0.5) * 3.0 * step(0.02, u_p) + px * (1.0 - step(0.02, u_p)), u_outSize); n = sampleIn(u_in, mix((cell + 0.5) * 3.0, px, step(0.98, u_p)), u_inSize); tOut = mix(bayer(cell), sweep, bias); tIn = tOut; } else { // Noise: a soft value-noise field with a glowing edge. float v = vnoise(px / 26.0) * 0.65 + vnoise(px / 7.0) * 0.35; tOut = mix(v, sweep, bias); tIn = tOut; o = sampleIn(u_out, px, u_outSize); n = sampleIn(u_in, px, u_inSize); edge = 1.0 - smoothstep(0.0, 0.06, abs(tOut - p)); } float keepOut = step(p, tOut); float showIn = 1.0 - step(p, tIn); vec4 color = o * keepOut + n * showIn * (1.0 - keepOut); if (u_mode == 2 && u_p > 0.0 && u_p < 1.0) color.rgb = mix(color.rgb, u_edge, edge * 0.85) ; if (u_mode == 2 && u_p > 0.0 && u_p < 1.0) color.a = max(color.a, edge * 0.85); outColor = color; }`; const MODES = { pixel: 0, dither: 1, noise: 2 } as const; const DIRS = { none: [0, 0], up: [0, -1], down: [0, 1], left: [-1, 0], right: [1, 0] } as const; type Slot = { key: string | number; node: ReactNode }; /** * A wrapper for swapping content (tabs, steps, routes) through HTML-in-Canvas: the outgoing live DOM * dissolves into pixel blocks, dither dots or noise while the incoming DOM resolves out of the same * pattern. Without the API, or with reduced motion, it crossfades with a blur (a plain fade under * reduced motion). */ export function DissolveTransition({ contentKey, children, mode = "pixel", duration = 0.9, direction = "none", edgeColor = "var(--primary)", rendering = "auto", onModeChange, onTransitionEnd, className, }: DissolveTransitionProps) { const reduceMotion = useReducedMotion(); const [current, setCurrent] = useState<Slot>({ key: contentKey, node: children }); const [outgoing, setOutgoing] = useState<Slot | null>(null); // New key: the old content becomes the outgoing slot. Same key: keep the content fresh. if (contentKey !== current.key) { setOutgoing(current); setCurrent({ key: contentKey, node: children }); } else if (children !== current.node) { setCurrent({ key: contentKey, node: children }); } const inRef = useRef<HTMLDivElement>(null); const outRef = useRef<HTMLDivElement>(null); const [height, setHeight] = useState<number | null>(null); const transition = useRef({ start: -1, captured: false, frames: 0 }); // The edge color resolved to RGB (it may be a theme variable), recomputed only when it changes. const edge = useRef<{ color: string; rgb: Vec3 } | null>(null); const gl = useRef<{ program: Program; mesh: Mesh; tin: ElementTexture; tout: ElementTexture } | null>(null); const { native, canvasRef, canvasProps, invalidate } = useHtmlCanvas({ context: "webgl2", mode: rendering, animating: outgoing !== null, setup: (ctx) => { gl.current = { program: createProgram(ctx, VERT, FRAG), mesh: createGrid(ctx), tin: createElementTexture(ctx), tout: createElementTexture(ctx) }; return () => { if (!gl.current) return; ctx.deleteProgram(gl.current.program.program); ctx.deleteTexture(gl.current.tin.texture); ctx.deleteTexture(gl.current.tout.texture); gl.current = null; }; }, render: ({ ctx, canvas, width, height: h, reason, changed }) => { const g = gl.current; const incoming = inRef.current; if (!g || !incoming) return; const out = outRef.current; if (reason !== "frame" || !g.tin.width) { uploadElementTexture(ctx, g.tin, incoming); syncElementGeometry(canvas, incoming, new DOMMatrix()); } let p = 1; if (out) { const tr = transition.current; if (!tr.captured) { // Capture the outgoing content once the browser has painted it in its new slot; until then // draw nothing, so the canvas keeps showing the last frame. tr.frames += 1; const painted = reason === "paint" && changed.some((el) => el === out || out.contains(el)); if (!painted && tr.frames < 6) return; uploadElementTexture(ctx, g.tout, out); uploadElementTexture(ctx, g.tin, incoming); transition.current = { start: performance.now(), captured: true, frames: tr.frames }; } p = Math.min(1, (performance.now() - transition.current.start) / 1000 / Math.max(0.1, duration)); if (p >= 1) window.setTimeout(() => setOutgoing(null), 0); } ctx.viewport(0, 0, canvas.width, canvas.height); ctx.clearColor(0, 0, 0, 0); ctx.clear(ctx.COLOR_BUFFER_BIT); ctx.enable(ctx.BLEND); ctx.blendFunc(ctx.ONE, ctx.ONE_MINUS_SRC_ALPHA); ctx.useProgram(g.program.program); const { u } = g.program; ctx.uniform2f(u("u_canvas"), width, h); ctx.uniform2f(u("u_size"), width, h); ctx.uniform2f(u("u_inSize"), g.tin.width || width, g.tin.height || h); ctx.uniform2f(u("u_outSize"), g.tout.width || width, g.tout.height || h); ctx.uniform1f(u("u_p"), out ? p : 1); ctx.uniform1i(u("u_mode"), MODES[mode]); ctx.uniform2f(u("u_dir"), DIRS[direction][0], DIRS[direction][1]); if (edge.current?.color !== edgeColor) edge.current = { color: edgeColor, rgb: cssColorToVec3(edgeColor, canvas) }; ctx.uniform3f(u("u_edge"), ...edge.current.rgb); ctx.activeTexture(ctx.TEXTURE0); ctx.bindTexture(ctx.TEXTURE_2D, g.tout.texture); ctx.uniform1i(u("u_out"), 0); ctx.activeTexture(ctx.TEXTURE1); ctx.bindTexture(ctx.TEXTURE_2D, g.tin.texture); ctx.uniform1i(u("u_in"), 1); drawMesh(ctx, g.mesh); }, }); useEffect(() => onModeChange?.(native), [native, onModeChange]); // The edge color is resolved on the next frame after a theme switch. useEffect(() => observeTheme(() => (edge.current = null)), []); // A new outgoing slot starts a new transition; finishing one reports it. useLayoutEffect(() => { transition.current = { start: -1, captured: false, frames: 0 }; if (outgoing) invalidate(); }, [outgoing, invalidate]); const hadOutgoing = useRef(false); useEffect(() => { if (hadOutgoing.current && !outgoing) onTransitionEnd?.(); hadOutgoing.current = outgoing !== null; }, [outgoing, onTransitionEnd]); // In native mode the canvas is as tall as the taller of the two contents. useEffect(() => { if (!native) return; const measure = () => setHeight(Math.max(inRef.current?.offsetHeight ?? 0, outRef.current?.offsetHeight ?? 0)); const observer = new ResizeObserver(measure); if (inRef.current) observer.observe(inRef.current); if (outRef.current) observer.observe(outRef.current); measure(); return () => observer.disconnect(); }, [native, outgoing, current.key]); if (!native) { return ( <div className={cn("grid w-full [&>*]:[grid-area:1/1]", className)}> <AnimatePresence initial={false}> <motion.div key={current.key} initial={reduceMotion ? { opacity: 0 } : { opacity: 0, filter: "blur(8px)" }} animate={{ opacity: 1, filter: "blur(0px)" }} exit={reduceMotion ? { opacity: 0 } : { opacity: 0, filter: "blur(8px)" }} transition={{ duration: reduceMotion ? 0.2 : duration * 0.7, ease: ease.out }} onAnimationComplete={() => onTransitionEnd?.()} > {current.node} </motion.div> </AnimatePresence> </div> ); } return ( <div className={cn("relative w-full", className)} style={{ height: height ?? undefined }}> <canvas ref={canvasRef} {...canvasProps} className="absolute inset-0 block size-full"> <div ref={inRef} key={`in-${current.key}`} className="w-full"> {current.node} </div> {outgoing ? ( <div ref={outRef} key={`out-${outgoing.key}`} className="pointer-events-none w-full" aria-hidden="true" inert> {outgoing.node} </div> ) : null} </canvas> </div> ); }
Usage
import { DissolveTransition } from "@/components/ui/dissolve-transition/dissolve-transition";
<DissolveTransition contentKey={tab} mode="pixel">
<TabPanel tab={tab} />
</DissolveTransition>API reference
| Prop | Type | Default | Description |
|---|---|---|---|
contentKey* | string | number | – | Identifies the current content. Changing it dissolves the old content into the new. |
children* | ReactNode | – | The current content. |
mode | "pixel" | "dither" | "noise" | "pixel" | How content breaks up: growing pixel blocks, an ordered dither or a noise field. |
duration | number | 0.9 | Seconds the swap takes. |
direction | "none" | "up" | "down" | "left" | "right" | "none" | Where the dissolve starts sweeping from; "none" dissolves everywhere at once. |
edgeColor | string | "var(--primary)" | Color of the glowing edge in noise mode. |
rendering | HtmlCanvasMode | "auto" | "auto" uses HTML-in-Canvas when available, "fallback" never does. |
onModeChange | (native: boolean) => void | – | Called when the rendering mode is known. |
onTransitionEnd | () => void | – | Called when a transition finishes. |
className | string | – | 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 outgoing content is captured once, after the browser has painted it; only the incoming texture updates while you interact with it. The frame loop runs only during a transition.
- Change `contentKey` to transition. Changing children with the same key updates the content in place without a dissolve.
Accessibility
- Only the incoming content is interactive and in the accessibility tree; the outgoing copy is inert and aria-hidden while it dissolves, and is removed when the transition ends.
- The incoming content's geometry is synced to where it is drawn, so focus, clicks and text selection work during and after the swap.
- With reduced motion, or without the HTML-in-Canvas API, content crossfades with a blur (a plain fade under reduced motion).