Skip to content

Write HTML. Render video. Built for agents.

fix: resolve merge conflict in shader-transitions capture.ts

Miguel Ángel6ef52972fd5b
diff --cc packages/shader-transitions/README.md
index 14073d727b,d42ddfc11c..d6222cf420
--- a/packages/shader-transitions/README.md
+++ b/packages/shader-transitions/README.md
@@@ -30,13 -30,8 +30,13 @@@ const tl = init(
});
```
- The `init()` function captures each scene to a WebGL texture at transition time, crossfades between them using the selected shader, and returns a GSAP timeline. If WebGL is unavailable, it falls back to hard cuts.
+ The `init()` function pre-captures animated scene samples for every transition, composites cached samples with the selected shader during playback, and returns a GSAP timeline. Scene animations keep advancing through shader transitions without running DOM captures in the playback loop. If WebGL is unavailable, it falls back to normal timeline playback without shader compositing.
+When the browser exposes Chrome's experimental CanvasDrawElement API, scene
+capture uses native HTML-in-canvas via `drawElementImage()`. Other browsers keep
+using the existing `html2canvas` fallback. You can feature-detect the native path
+with `isHtmlInCanvasCaptureSupported()`.
+
### With an existing timeline
Pass your own GSAP timeline to layer transitions onto it:
diff --cc packages/shader-transitions/src/capture.ts
index e45862e79f,5b983d16b9..7f97f9a45d
--- a/packages/shader-transitions/src/capture.ts
+++ b/packages/shader-transitions/src/capture.ts
@@@ -76,188 -90,66 +90,144 @@@ function stabilizeTransformedBoxShadows
});
}
- function waitForPaint(canvas: CanvasWithLayoutSubtree): Promise<void> {
- return new Promise((resolve, reject) => {
- const timeout = setTimeout(() => {
- canvas.removeEventListener("paint", onPaint);
- reject(new Error("Timed out waiting for canvas paint event"));
- }, 1000);
++// ── HTML-in-Canvas (drawElementImage) native capture ──────────────────────
++
++interface CanvasWithLayoutSubtree extends HTMLCanvasElement {
++ layoutSubtree: boolean;
++ requestPaint: () => void;
++}
+
- const onPaint = () => {
- clearTimeout(timeout);
- resolve();
- };
++interface CanvasRenderingContext2DWithDrawElement extends CanvasRenderingContext2D {
++ drawElementImage: (element: Element, x: number, y: number, w: number, h: number) => void;
++}
+
- canvas.addEventListener("paint", onPaint, { once: true });
- canvas.requestPaint();
- });
++function hasLayoutSubtreeCanvas(canvas: HTMLCanvasElement): canvas is CanvasWithLayoutSubtree {
++ const candidate = canvas as HTMLCanvasElement & {
++ layoutSubtree?: unknown;
++ requestPaint?: unknown;
++ };
++ return "layoutSubtree" in candidate && typeof candidate.requestPaint === "function";
++}
++
++export function isHtmlInCanvasCaptureSupported(): boolean {
++ if (typeof document === "undefined") return false;
++ const probe = document.createElement("canvas") as HTMLCanvasElement & {
++ layoutSubtree?: boolean;
++ };
++ probe.setAttribute("layoutsubtree", "");
++ if (!("layoutSubtree" in probe)) return false;
++ const ctx = probe.getContext("2d") as CanvasRenderingContext2DWithDrawElement | null;
++ return ctx != null && typeof ctx.drawElementImage === "function";
+}
+
+async function captureSceneWithHtmlInCanvas(
+ sceneEl: HTMLElement,
+ bgColor: string,
+ width: number,
+ height: number,
+): Promise<HTMLCanvasElement> {
- const canvas = document.createElement("canvas");
- if (!hasLayoutSubtreeCanvas(canvas)) {
- throw new Error("HTML-in-canvas layoutsubtree support is unavailable");
- }
-
- const ctx = getDrawElementImageContext(canvas);
- if (!ctx) {
- throw new Error("HTML-in-canvas drawElementImage support is unavailable");
- }
-
- const clone = sceneEl.cloneNode(true);
- if (!(clone instanceof HTMLElement)) {
- throw new Error("Scene clone is not an HTMLElement");
- }
-
++ const canvas = document.createElement("canvas") as CanvasWithLayoutSubtree;
+ canvas.width = width;
+ canvas.height = height;
- canvas.layoutSubtree = true;
+ canvas.setAttribute("layoutsubtree", "");
- canvas.style.cssText = [
- "position:fixed",
- "left:0",
- "top:0",
- `width:${width}px`,
- `height:${height}px`,
- "pointer-events:none",
- "opacity:0.001",
- "z-index:-2147483648",
- ].join(";");
-
- clone.style.position = "absolute";
- clone.style.left = "0";
- clone.style.top = "0";
- clone.style.width = `${width}px`;
- clone.style.height = `${height}px`;
-
- canvas.appendChild(clone);
++ canvas.style.cssText = `position:fixed;top:0;left:0;width:${width}px;height:${height}px;z-index:-9999;pointer-events:none;opacity:0`;
++ canvas.appendChild(sceneEl.cloneNode(true));
+ document.body.appendChild(canvas);
+
+ try {
- await waitForNextFrame();
- await waitForPaint(canvas);
-
- ctx.setTransform(1, 0, 0, 1, 0, 0);
- ctx.clearRect(0, 0, width, height);
++ await new Promise<void>((r) => requestAnimationFrame(() => requestAnimationFrame(() => r())));
++ const ctx = canvas.getContext("2d") as CanvasRenderingContext2DWithDrawElement;
+ ctx.fillStyle = bgColor;
+ ctx.fillRect(0, 0, width, height);
- ctx.drawElementImage(clone, 0, 0, width, height);
++ const child = canvas.firstElementChild;
++ if (child) ctx.drawElementImage(child, 0, 0, width, height);
++ const result = document.createElement("canvas");
++ result.width = width;
++ result.height = height;
++ result.getContext("2d")!.drawImage(canvas, 0, 0);
+ canvas.remove();
- return canvas;
++ return result;
+ } catch (err) {
+ canvas.remove();
+ throw err;
+ }
+}
+
- function captureSceneWithHtml2Canvas(
- sceneEl: HTMLElement,
- bgColor: string,
- width: number = DEFAULT_WIDTH,
- height: number = DEFAULT_HEIGHT,
- ): Promise<HTMLCanvasElement> {
- return html2canvas(sceneEl, {
- width,
- height,
- scale: 1,
- backgroundColor: bgColor,
- logging: false,
- // Safari applies stricter canvas-taint rules than Chrome. SVG data URLs
- // with <filter> elements (e.g. feTurbulence grain backgrounds), certain
- // cross-origin images, and mask/clip-path url() refs can taint the
- // output canvas on WebKit. Without these flags, html2canvas throws
- // `SecurityError: The operation is insecure` during its own read-back
- // path and every shader transition falls through to the catch handler
- // — observed in Safari + Claude Design's cross-origin iframe sandbox.
- //
- // useCORS: send CORS headers on image fetches so cross-origin images
- // with proper `Access-Control-Allow-Origin` don't taint the
- // canvas in the first place. Strict improvement.
- // allowTaint: let html2canvas complete and return a canvas even when it
- // becomes tainted (instead of throwing). Important caveat:
- // a tainted canvas CANNOT be uploaded to WebGL via
- // `gl.texImage2D` — WebGL spec requires SecurityError on
- // non-origin-clean sources, with no opt-out. So this flag
- // only moves the failure point from html2canvas to the
- // texImage2D call in webgl.ts. In both cases `hyper-shader.ts`
- // catches the rejected promise and runs the CSS crossfade
- // fallback. Net effect: the end-user UX is the same (smooth
- // CSS fade in either case), but we get a cleaner, more
- // predictable error site and the flag is defensively
- // correct for the non-taint branches where it genuinely
- // helps (e.g., `crossOrigin="anonymous"` image fetches
- // that already had CORS headers).
- useCORS: true,
- allowTaint: true,
- ignoreElements: (el: Element) => el.tagName === "CANVAS" || el.hasAttribute("data-no-capture"),
- });
- }
-
export function captureScene(
sceneEl: HTMLElement,
bgColor: string,
width: number = DEFAULT_WIDTH,
height: number = DEFAULT_HEIGHT,
+ options: CaptureSceneOptions = {},
+): Promise<HTMLCanvasElement> {
- if (!isHtmlInCanvasCaptureSupported()) {
- return captureSceneWithHtml2Canvas(sceneEl, bgColor, width, height);
++ if (isHtmlInCanvasCaptureSupported() && !options.preferBrowserPaint) {
++ return captureSceneWithHtmlInCanvas(sceneEl, bgColor, width, height).catch(() =>
++ captureSceneWithHtml2Canvas(sceneEl, bgColor, width, height, options),
++ );
+ }
-
- return captureSceneWithHtmlInCanvas(sceneEl, bgColor, width, height).catch(() =>
- captureSceneWithHtml2Canvas(sceneEl, bgColor, width, height),
- );
++ return captureSceneWithHtml2Canvas(sceneEl, bgColor, width, height, options);
+}
+
- /**
- * Capture the incoming scene with .scene-content hidden (background + decoratives only).
- * Shows the scene behind the outgoing scene via z-index, waits 2 rAFs for font rendering,
- * captures, then restores.
- *
- * IMPORTANT: We force `visibility: visible` during capture because the HyperFrames runtime's
- * time-based visibility gate (in `packages/core/src/runtime/init.ts`) sets `style.visibility
- * = "hidden"` on every `[data-start]` element that's outside its current playback window —
- * every frame. When a shader transition fires *before* the incoming scene's `data-start`
- * boundary (the recommended "transition.time = boundary - duration/2" centered placement),
- * the runtime has `visibility: hidden` on the incoming scene. Without the visibility override
- * here, `html2canvas` captures the element as blank → shader transitions from the real
- * outgoing scene to a blank incoming texture → users see content fade/morph into the
- * background color mid-transition (a visible "blink"). Forcing `visibility: visible` only
- * for the duration of the capture fixes this without affecting what the user sees during
- * normal playback.
- */
- export function captureIncomingScene(
- toScene: HTMLElement,
++function captureSceneWithHtml2Canvas(
++ sceneEl: HTMLElement,
+ bgColor: string,
- width: number = DEFAULT_WIDTH,
- height: number = DEFAULT_HEIGHT,
++ width: number,
++ height: number,
++ options: CaptureSceneOptions = {},
): Promise<HTMLCanvasElement> {
- return new Promise<HTMLCanvasElement>((resolve, reject) => {
- const origZ = toScene.style.zIndex;
- const origOpacity = toScene.style.opacity;
- const origVisibility = toScene.style.visibility;
- toScene.style.zIndex = "-1";
- toScene.style.opacity = "1";
- toScene.style.visibility = "visible";
-
- const contentEl = toScene.querySelector<HTMLElement>(".scene-content");
- if (contentEl) contentEl.style.visibility = "hidden";
+ const captureWithRenderer = (foreignObjectRendering: boolean): Promise<HTMLCanvasElement> => {
+ return html2canvas(sceneEl, {
+ width,
+ height,
+ scale: options.scale ?? 1,
+ backgroundColor: bgColor,
+ logging: false,
+ foreignObjectRendering,
+ // Safari applies stricter canvas-taint rules than Chrome. SVG data URLs
+ // with <filter> elements (e.g. feTurbulence grain backgrounds), certain
+ // cross-origin images, and mask/clip-path url() refs can taint the
+ // output canvas on WebKit. Without these flags, html2canvas throws
+ // `SecurityError: The operation is insecure` during its own read-back
+ // path and every shader transition falls through to the catch handler
+ // — observed in Safari + Claude Design's cross-origin iframe sandbox.
+ //
+ // useCORS: send CORS headers on image fetches so cross-origin images
+ // with proper `Access-Control-Allow-Origin` don't taint the
+ // canvas in the first place. Strict improvement.
+ // allowTaint: let html2canvas complete and return a canvas even when it
+ // becomes tainted (instead of throwing). Important caveat:
+ // a tainted canvas CANNOT be uploaded to WebGL via
+ // `gl.texImage2D` — WebGL spec requires SecurityError on
+ // non-origin-clean sources, with no opt-out. So this flag
+ // only moves the failure point from html2canvas to the
+ // texImage2D call in webgl.ts. The caller catches the
+ // rejected promise and keeps the DOM fallback visible. Net
+ // effect: the end-user UX avoids blank frames either way,
+ // but we get a cleaner, more predictable error site and the
+ // flag is defensively correct for the non-taint branches
+ // where it genuinely helps (e.g.,
+ // `crossOrigin="anonymous"` image fetches that already had
+ // CORS headers).
+ useCORS: true,
+ allowTaint: true,
+ onclone: (cloneDoc) => {
+ if (!sceneEl.id) return;
+ const clone = cloneDoc.getElementById(sceneEl.id);
+ if (clone instanceof HTMLElement) {
+ stabilizeTransformedBoxShadows(clone);
+ }
+ if (options.forceVisible) {
+ forceSceneVisibleInClone(sceneEl, cloneDoc);
+ }
+ },
+ ignoreElements: (el: Element) =>
+ el.tagName === "CANVAS" || el.hasAttribute("data-no-capture"),
+ });
+ };
- const restore = () => {
- if (contentEl) contentEl.style.visibility = "";
- toScene.style.visibility = origVisibility;
- toScene.style.opacity = origOpacity;
- toScene.style.zIndex = origZ;
- };
+ if (options.preferBrowserPaint === true) {
+ return captureWithRenderer(true).catch(() => captureWithRenderer(false));
+ }
- requestAnimationFrame(() => {
- requestAnimationFrame(() => {
- captureScene(toScene, bgColor, width, height).then(resolve, reject).finally(restore);
- });
- });
- });
+ return captureWithRenderer(false);
}