Skip to content

🎥 Make videos programmatically with React

cool

Jonny Burger19390cca6ed1
diff --git a/packages/core/src/canvas-effects/HtmlInCanvas.tsx b/packages/core/src/canvas-effects/HtmlInCanvas.tsx
index 25fb799428..bb235744ce 100644
--- a/packages/core/src/canvas-effects/HtmlInCanvas.tsx
+++ b/packages/core/src/canvas-effects/HtmlInCanvas.tsx
@@ -1,18 +1,14 @@
import React, {useCallback, useEffect, useRef, useState} from 'react';
-import {cancelRender} from '../cancel-render.js';
+import {useCurrentFrame} from '../use-current-frame.js';
+import {useDelayRender} from '../use-delay-render.js';
import type {EffectsProp} from './effect-types.js';
-import {useEffectChain} from './use-effect-chain.js';
-
-// Type augmentation for the WICG html-in-canvas proposal:
-// https://github.com/WICG/html-in-canvas
-//
-// Requires Chrome Canary with chrome://flags/#canvas-draw-element enabled, so
-// that both drawElementImage() and canvas.requestPaint() are available.
-//
-// The current Chromium implementation requires the element passed to
-// drawElementImage() to be an immediate child of the canvas, and the canvas
-// must have its `layoutSubtree` property set to true so the children are
-// actually laid out (instead of being treated as fallback content).
+import {
+ cleanupEffectChainState,
+ createEffectChainState,
+ runEffectChain,
+} from './run-effect-chain.js';
+import type {EffectChainState} from './run-effect-chain.js';
+
type Canvas2DWithDrawElement = CanvasRenderingContext2D & {
drawElementImage: (
element: Element,
@@ -53,12 +49,6 @@ export type HtmlInCanvasProps = {
readonly pixelRatio?: number;
};
-// `<HtmlInCanvas>` rasterizes its DOM children into a canvas using the WICG
-// html-in-canvas proposal, then runs the resulting image through an
-// effect chain. The captured DOM image is the source for the chain; effects
-// then transform it just like with any other source component.
-//
-// Requires Chrome Canary with `chrome://flags/#canvas-draw-element` enabled.
export const HtmlInCanvas: React.FC<HtmlInCanvasProps> = ({
width,
height,
@@ -66,14 +56,104 @@ export const HtmlInCanvas: React.FC<HtmlInCanvasProps> = ({
children,
className,
style,
- pixelRatio,
+ pixelRatio = 1,
}) => {
+ const frame = useCurrentFrame();
+ const {delayRender, continueRender, cancelRender} = useDelayRender();
+
const sourceCanvasRef = useRef<HTMLCanvasElement | null>(null);
const sceneRef = useRef<HTMLDivElement | null>(null);
const [outputCanvas, setOutputCanvas] = useState<HTMLCanvasElement | null>(
null,
);
+ const chainStateRef = useRef<EffectChainState | null>(null);
+ const sizeRef = useRef<{width: number; height: number} | null>(null);
+
+ if (
+ !sizeRef.current ||
+ sizeRef.current.width !== width ||
+ sizeRef.current.height !== height
+ ) {
+ if (chainStateRef.current) {
+ cleanupEffectChainState(chainStateRef.current);
+ }
+
+ chainStateRef.current = createEffectChainState(width, height);
+ sizeRef.current = {width, height};
+ }
+
+ // Refs so the paint handler always reads fresh values.
+ const effectsRef = useRef(effects);
+ effectsRef.current = effects;
+ const frameRef = useRef(frame);
+ frameRef.current = frame;
+ const pixelRatioRef = useRef(pixelRatio);
+ pixelRatioRef.current = pixelRatio;
+ const widthRef = useRef(width);
+ widthRef.current = width;
+ const heightRef = useRef(height);
+ heightRef.current = height;
+
+ // Track the current delayRender handle so the paint handler can settle it.
+ const pendingHandleRef = useRef<number | null>(null);
+
+ const onPaint = useCallback(() => {
+ const sourceCanvas =
+ sourceCanvasRef.current as HTMLCanvasWithLayoutSubtree | null;
+ const sceneEl = sceneRef.current;
+ const chainState = chainStateRef.current;
+ const output = outputCanvas;
+ const handle = pendingHandleRef.current;
+
+ if (
+ !sourceCanvas ||
+ !sceneEl ||
+ !chainState ||
+ !output ||
+ handle === null
+ ) {
+ return;
+ }
+
+ const ctx = sourceCanvas.getContext('2d') as Canvas2DWithDrawElement | null;
+ if (!ctx) {
+ cancelRender(
+ new Error('Failed to acquire 2D context for <HtmlInCanvas> source'),
+ );
+ return;
+ }
+
+ const w = widthRef.current;
+ const h = heightRef.current;
+
+ ctx.reset();
+ ctx.drawElementImage(sceneEl, 0, 0, w, h);
+
+ const capturedHandle = handle;
+ pendingHandleRef.current = null;
+
+ runEffectChain({
+ state: chainState,
+ source: sourceCanvas,
+ effects: effectsRef.current,
+ output,
+ frame: frameRef.current,
+ width: w,
+ height: h,
+ pixelRatio: pixelRatioRef.current,
+ })
+ .then((completed) => {
+ if (completed) {
+ continueRender(capturedHandle);
+ }
+ })
+ .catch((err) => {
+ cancelRender(err);
+ });
+ }, [outputCanvas, continueRender, cancelRender]);
+
+ // Set up layoutSubtree and persistent paint listener.
useEffect(() => {
if (!isHtmlInCanvasSupported()) {
cancelRender(
@@ -91,47 +171,43 @@ export const HtmlInCanvas: React.FC<HtmlInCanvasProps> = ({
}
sourceCanvas.layoutSubtree = true;
- }, []);
+ sourceCanvas.addEventListener('paint', onPaint);
+ return () => {
+ sourceCanvas.removeEventListener('paint', onPaint);
+ };
+ }, [onPaint, cancelRender]);
+
+ // On each frame change: block the renderer and request a paint.
+ useEffect(() => {
+ const handle = delayRender(`HtmlInCanvas (frame ${frame})`);
+
+ // Continue a stale handle from a previous frame that never got a paint.
+ if (pendingHandleRef.current !== null) {
+ continueRender(pendingHandleRef.current);
+ }
+
+ pendingHandleRef.current = handle;
- const source = useCallback(() => {
const sourceCanvas =
sourceCanvasRef.current as HTMLCanvasWithLayoutSubtree | null;
- const sceneEl = sceneRef.current;
- if (!sourceCanvas || !sceneEl) {
- return null;
- }
+ sourceCanvas?.requestPaint();
- const ctx = sourceCanvas.getContext('2d') as Canvas2DWithDrawElement | null;
- if (!ctx) {
- throw new Error('Failed to acquire 2D context for <HtmlInCanvas> source');
- }
+ return () => {
+ if (pendingHandleRef.current === handle) {
+ continueRender(handle);
+ pendingHandleRef.current = null;
+ }
+ };
+ }, [frame, delayRender, continueRender]);
- return new Promise<CanvasImageSource>((resolve, reject) => {
- const onPaint = () => {
- sourceCanvas.removeEventListener('paint', onPaint);
- try {
- ctx.reset();
- ctx.drawElementImage(sceneEl, 0, 0, width, height);
- resolve(sourceCanvas);
- } catch (err) {
- reject(err instanceof Error ? err : new Error(String(err)));
- }
- };
-
- sourceCanvas.addEventListener('paint', onPaint);
- sourceCanvas.requestPaint();
- });
- }, [width, height]);
-
- useEffectChain({
- source,
- effects,
- width,
- height,
- pixelRatio,
- output: outputCanvas,
- sourceDeps: [],
- });
+ // Cleanup chain state on unmount.
+ useEffect(() => {
+ return () => {
+ if (chainStateRef.current) {
+ cleanupEffectChainState(chainStateRef.current);
+ }
+ };
+ }, []);
return (
<>
diff --git a/packages/core/src/canvas-effects/Solid.tsx b/packages/core/src/canvas-effects/Solid.tsx
index 5c9ba55801..bd5ae04239 100644
--- a/packages/core/src/canvas-effects/Solid.tsx
+++ b/packages/core/src/canvas-effects/Solid.tsx
@@ -1,6 +1,13 @@
-import React, {useCallback, useMemo, useState} from 'react';
+import React, {useEffect, useMemo, useRef, useState} from 'react';
+import {useCurrentFrame} from '../use-current-frame.js';
+import {useDelayRender} from '../use-delay-render.js';
import type {EffectsProp} from './effect-types.js';
-import {useEffectChain} from './use-effect-chain.js';
+import {
+ cleanupEffectChainState,
+ createEffectChainState,
+ runEffectChain,
+} from './run-effect-chain.js';
+import type {EffectChainState} from './run-effect-chain.js';
export type SolidProps = {
readonly color: string;
@@ -12,14 +19,6 @@ export type SolidProps = {
readonly pixelRatio?: number;
};
-// `<Solid>` is the simplest source component: it produces a flat-color image
-// to feed into the canvas-effect chain. Combined with an effect chain it can
-// generate procedural content (gradients, blurs, noise patches, ...) without
-// needing to mount a DOM source.
-//
-// Internally the source is a 1x1 canvas filled with `color`; the chain runtime
-// scales it to the chain's `width`/`height` when the next stage samples it,
-// which is correct because every pixel is the same color.
export const Solid: React.FC<SolidProps> = ({
color,
width,
@@ -27,8 +26,11 @@ export const Solid: React.FC<SolidProps> = ({
effects = [],
className,
style,
- pixelRatio,
+ pixelRatio = 1,
}) => {
+ const frame = useCurrentFrame();
+ const {delayRender, continueRender, cancelRender} = useDelayRender();
+
const [outputCanvas, setOutputCanvas] = useState<HTMLCanvasElement | null>(
null,
);
@@ -44,30 +46,86 @@ export const Solid: React.FC<SolidProps> = ({
return canvas;
}, []);
- const source = useCallback(() => {
- if (!sourceCanvas) {
- return null;
+ const chainStateRef = useRef<EffectChainState | null>(null);
+ const sizeRef = useRef<{width: number; height: number} | null>(null);
+
+ if (
+ !sizeRef.current ||
+ sizeRef.current.width !== width ||
+ sizeRef.current.height !== height
+ ) {
+ if (chainStateRef.current) {
+ cleanupEffectChainState(chainStateRef.current);
+ }
+
+ chainStateRef.current = createEffectChainState(width, height);
+ sizeRef.current = {width, height};
+ }
+
+ // Fill source and run effect chain on every frame / color change.
+ useEffect(() => {
+ if (!outputCanvas || !sourceCanvas || !chainStateRef.current) {
+ return;
}
+ const handle = delayRender(`Solid effect chain (frame ${frame})`);
+
const ctx = sourceCanvas.getContext('2d', {colorSpace: 'srgb'});
if (!ctx) {
- throw new Error('Failed to acquire 2D context for <Solid> source');
+ cancelRender(
+ new Error('Failed to acquire 2D context for <Solid> source'),
+ );
+ return;
}
ctx.fillStyle = color;
ctx.fillRect(0, 0, 1, 1);
- return sourceCanvas;
- }, [color, sourceCanvas]);
- useEffectChain({
- source,
+ runEffectChain({
+ state: chainStateRef.current,
+ source: sourceCanvas,
+ effects,
+ output: outputCanvas,
+ frame,
+ width,
+ height,
+ pixelRatio,
+ })
+ .then((completed) => {
+ if (completed) {
+ continueRender(handle);
+ }
+ })
+ .catch((err) => {
+ cancelRender(err);
+ });
+
+ return () => {
+ continueRender(handle);
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [
+ frame,
+ color,
effects,
+ outputCanvas,
+ sourceCanvas,
width,
height,
pixelRatio,
- output: outputCanvas,
- sourceDeps: [color],
- });
+ delayRender,
+ continueRender,
+ cancelRender,
+ ]);
+
+ // Cleanup chain state on unmount.
+ useEffect(() => {
+ return () => {
+ if (chainStateRef.current) {
+ cleanupEffectChainState(chainStateRef.current);
+ }
+ };
+ }, []);
return (
<canvas
diff --git a/packages/core/src/canvas-effects/run-effect-chain.ts b/packages/core/src/canvas-effects/run-effect-chain.ts
new file mode 100644
index 0000000000..f5e7c36e36
--- /dev/null
+++ b/packages/core/src/canvas-effects/run-effect-chain.ts
@@ -0,0 +1,170 @@
+import {CanvasPool} from './canvas-pool.js';
+import {flattenEffects, groupByBackend} from './effect-internals.js';
+import type {EffectDefinition, EffectsProp} from './effect-types.js';
+import {getGpuDevice} from './gpu-device.js';
+
+export type EffectChainState = {
+ pool: CanvasPool;
+ setupCache: WeakMap<EffectDefinition<unknown, unknown>, Promise<unknown>>;
+ cleanupRegistry: Array<{
+ definition: EffectDefinition<unknown, unknown>;
+ statePromise: Promise<unknown>;
+ }>;
+ currentRunId: number;
+};
+
+export const createEffectChainState = (
+ width: number,
+ height: number,
+): EffectChainState => ({
+ pool: new CanvasPool(width, height),
+ setupCache: new WeakMap(),
+ cleanupRegistry: [],
+ currentRunId: 0,
+});
+
+export const cleanupEffectChainState = (state: EffectChainState): void => {
+ state.currentRunId++;
+ for (const entry of state.cleanupRegistry) {
+ entry.statePromise.then(
+ (s) => entry.definition.cleanup?.(s),
+ () => undefined,
+ );
+ }
+};
+
+const ensureSetup = (
+ state: EffectChainState,
+ def: EffectDefinition<unknown, unknown>,
+ target: HTMLCanvasElement,
+): Promise<unknown> => {
+ const cached = state.setupCache.get(def);
+ if (cached) {
+ return cached;
+ }
+
+ const promise = Promise.resolve(def.setup(target));
+ state.setupCache.set(def, promise);
+ state.cleanupRegistry.push({definition: def, statePromise: promise});
+ return promise;
+};
+
+export type RunEffectChainOptions = {
+ readonly state: EffectChainState;
+ readonly source: CanvasImageSource;
+ readonly effects: EffectsProp;
+ readonly output: HTMLCanvasElement;
+ readonly frame: number;
+ readonly width: number;
+ readonly height: number;
+ readonly pixelRatio: number;
+};
+
+// Runs the effect pipeline imperatively. Returns `true` if the pipeline
+// completed and wrote to `output`, `false` if it was superseded by a newer
+// run (caller should not act on a stale result).
+export const runEffectChain = async ({
+ state,
+ source,
+ effects,
+ output,
+ frame,
+ width,
+ height,
+ pixelRatio,
+}: RunEffectChainOptions): Promise<boolean> => {
+ const runId = ++state.currentRunId;
+ const isCancelled = () => state.currentRunId !== runId;
+
+ const flattened = flattenEffects(effects);
+ const runs = groupByBackend(flattened);
+
+ let currentImage: CanvasImageSource = source;
+ let lastTarget: HTMLCanvasElement | null = null;
+
+ if (runs.length === 0) {
+ const ctx = output.getContext('2d');
+ if (!ctx) {
+ throw new Error('Failed to acquire 2D context for output canvas');
+ }
+
+ ctx.clearRect(0, 0, width, height);
+ ctx.drawImage(currentImage, 0, 0, width, height);
+ return true;
+ }
+
+ let needsGpuDevice = false;
+ for (const run of runs) {
+ if (run.backend === 'webgpu') {
+ needsGpuDevice = true;
+ break;
+ }
+ }
+
+ const gpuDevice = needsGpuDevice ? await getGpuDevice() : null;
+ if (isCancelled()) {
+ return false;
+ }
+
+ for (let runIndex = 0; runIndex < runs.length; runIndex++) {
+ const run = runs[runIndex];
+ const [a, b] = state.pool.getPair(run.backend);
+ let dst = a;
+
+ for (const eff of run.effects) {
+ const def = eff.definition as EffectDefinition<unknown, unknown>;
+ const setupState = await ensureSetup(state, def, dst);
+ if (isCancelled()) {
+ return false;
+ }
+
+ await def.apply({
+ source: currentImage,
+ target: dst,
+ state: setupState,
+ params: eff.params,
+ frame,
+ width,
+ height,
+ pixelRatio,
+ gpuDevice,
+ });
+ if (isCancelled()) {
+ return false;
+ }
+
+ if (run.backend === 'webgl2') {
+ state.pool.assertContextNotLost(dst);
+ }
+
+ currentImage = dst;
+ dst = dst === a ? b : a;
+ }
+
+ lastTarget = (currentImage as HTMLCanvasElement | null) ?? lastTarget;
+
+ const nextRun = runs[runIndex + 1];
+ if (nextRun && nextRun.backend !== run.backend && lastTarget) {
+ const bitmap = await createImageBitmap(lastTarget);
+ if (isCancelled()) {
+ bitmap.close?.();
+ return false;
+ }
+
+ currentImage = bitmap;
+ }
+ }
+
+ if (!lastTarget) {
+ return true;
+ }
+
+ const outCtx = output.getContext('2d');
+ if (!outCtx) {
+ throw new Error('Failed to acquire 2D context for output canvas');
+ }
+
+ outCtx.clearRect(0, 0, width, height);
+ outCtx.drawImage(lastTarget, 0, 0, width, height);
+ return true;
+};
diff --git a/packages/core/src/canvas-effects/use-effect-chain.ts b/packages/core/src/canvas-effects/use-effect-chain.ts
deleted file mode 100644
index 2612bbddec..0000000000
--- a/packages/core/src/canvas-effects/use-effect-chain.ts
+++ /dev/null
@@ -1,270 +0,0 @@
-import {useEffect, useMemo, useRef} from 'react';
-import {useCurrentFrame} from '../use-current-frame.js';
-import {useDelayRender} from '../use-delay-render.js';
-import {CanvasPool} from './canvas-pool.js';
-import {flattenEffects, groupByBackend} from './effect-internals.js';
-import type {EffectDefinition, EffectsProp} from './effect-types.js';
-import {getGpuDevice} from './gpu-device.js';
-
-type SourceFn = () =>
- | CanvasImageSource
- | Promise<CanvasImageSource>
- | null
- | undefined;
-
-export type UseEffectChainOptions = {
- readonly source: SourceFn;
- readonly effects: EffectsProp;
- readonly width: number;
- readonly height: number;
- readonly pixelRatio?: number;
- readonly output: HTMLCanvasElement | null;
- // Stable React-deps to re-trigger the effect when callers change anything
- // that should invalidate the source (e.g. children, color, ...).
- readonly sourceDeps: ReadonlyArray<unknown>;
-};
-
-// Per-chain runtime state. Owned by the hook; recreated when width/height
-// change (since the canvas pool is sized at construction).
-type ChainState = {
- pool: CanvasPool;
- setupCache: WeakMap<EffectDefinition<unknown, unknown>, Promise<unknown>>;
- cleanupRegistry: Array<{
- definition: EffectDefinition<unknown, unknown>;
- statePromise: Promise<unknown>;
- }>;
-};
-
-const ensureSetup = (
- state: ChainState,
- def: EffectDefinition<unknown, unknown>,
- target: HTMLCanvasElement,
-): Promise<unknown> => {
- const cached = state.setupCache.get(def);
- if (cached) {
- return cached;
- }
-
- const promise = Promise.resolve(def.setup(target));
- state.setupCache.set(def, promise);
- state.cleanupRegistry.push({definition: def, statePromise: promise});
- return promise;
-};
-
-// `useEffectChain` is the shared per-frame runtime that powers source
-// components like `<Solid>` and `<HtmlInCanvas>`. Source components are
-// responsible for producing a `CanvasImageSource` via the `source` callback;
-// the runtime owns the rest of the pipeline (scratch canvases, ping-pong,
-// cross-backend transfer via `createImageBitmap`, single `delayRender` per
-// frame).
-export const useEffectChain = ({
- source,
- effects,
- width,
- height,
- pixelRatio = 1,
- output,
- sourceDeps,
-}: UseEffectChainOptions): void => {
- const frame = useCurrentFrame();
- const {delayRender, continueRender, cancelRender} = useDelayRender();
-
- const stateRef = useRef<ChainState | null>(null);
- const sizeRef = useRef<{width: number; height: number} | null>(null);
-
- // Reset pool if dimensions changed.
- if (
- !sizeRef.current ||
- sizeRef.current.width !== width ||
- sizeRef.current.height !== height
- ) {
- stateRef.current = {
- pool: new CanvasPool(width, height),
- setupCache: new WeakMap(),
- cleanupRegistry: [],
- };
- sizeRef.current = {width, height};
- }
-
- const flattened = useMemo(() => flattenEffects(effects), [effects]);
- const runs = useMemo(() => groupByBackend(flattened), [flattened]);
-
- useEffect(() => {
- const state = stateRef.current;
- if (!state || !output) {
- return;
- }
-
- const handle = delayRender(`Canvas effect chain (frame ${frame})`);
- let cancelled = false;
- let resolved = false;
-
- const finish = () => {
- if (resolved) {
- return;
- }
-
- resolved = true;
- continueRender(handle);
- };
-
- const fail = (err: unknown) => {
- if (resolved) {
- return;
- }
-
- resolved = true;
- cancelRender(err);
- };
-
- (async () => {
- try {
- const sourceImage = await source();
- if (cancelled) {
- return;
- }
-
- if (!sourceImage) {
- finish();
- return;
- }
-
- let currentImage: CanvasImageSource = sourceImage;
- let lastTarget: HTMLCanvasElement | null = null;
-
- if (runs.length === 0) {
- // No effects: blit source directly into output.
- const ctx = output.getContext('2d');
- if (!ctx) {
- throw new Error('Failed to acquire 2D context for output canvas');
- }
-
- ctx.clearRect(0, 0, width, height);
- ctx.drawImage(currentImage, 0, 0, width, height);
- finish();
- return;
- }
-
- let needsGpuDevice = false;
- for (const run of runs) {
- if (run.backend === 'webgpu') {
- needsGpuDevice = true;
- break;
- }
- }
-
- const gpuDevice = needsGpuDevice ? await getGpuDevice() : null;
- if (cancelled) {
- return;
- }
-
- for (let runIndex = 0; runIndex < runs.length; runIndex++) {
- const run = runs[runIndex];
- const [a, b] = state.pool.getPair(run.backend);
- let dst = a;
-
- for (const eff of run.effects) {
- const def = eff.definition as EffectDefinition<unknown, unknown>;
- const setupState = await ensureSetup(state, def, dst);
- if (cancelled) {
- return;
- }
-
- await def.apply({
- source: currentImage,
- target: dst,
- state: setupState,
- params: eff.params,
- frame,
- width,
- height,
- pixelRatio,
- gpuDevice,
- });
- if (cancelled) {
- return;
- }
-
- if (run.backend === 'webgl2') {
- state.pool.assertContextNotLost(dst);
- }
-
- currentImage = dst;
- dst = dst === a ? b : a;
- }
-
- lastTarget = (currentImage as HTMLCanvasElement | null) ?? lastTarget;
-
- // If another run follows with a different backend, transfer via
- // `createImageBitmap` so the next backend can sample from a
- // neutral GPU-resident handle.
- const nextRun = runs[runIndex + 1];
- if (nextRun && nextRun.backend !== run.backend && lastTarget) {
- const bitmap = await createImageBitmap(lastTarget);
- if (cancelled) {
- bitmap.close?.();
- return;
- }
-
- currentImage = bitmap;
- }
- }
-
- if (!lastTarget) {
- finish();
- return;
- }
-
- const outCtx = output.getContext('2d');
- if (!outCtx) {
- throw new Error('Failed to acquire 2D context for output canvas');
- }
-
- outCtx.clearRect(0, 0, width, height);
- outCtx.drawImage(lastTarget, 0, 0, width, height);
- finish();
- } catch (err) {
- if (!cancelled) {
- fail(err);
- }
- }
- })();
-
- return () => {
- cancelled = true;
- if (!resolved) {
- continueRender(handle);
- }
- };
- /* eslint-disable react-hooks/exhaustive-deps */
- }, [
- frame,
- width,
- height,
- pixelRatio,
- output,
- runs,
- delayRender,
- continueRender,
- cancelRender,
- ...sourceDeps,
- ]);
- /* eslint-enable react-hooks/exhaustive-deps */
-
- // Cleanup on unmount: invoke `cleanup` for every cached state.
- useEffect(() => {
- return () => {
- const state = stateRef.current;
- if (!state) {
- return;
- }
-
- for (const entry of state.cleanupRegistry) {
- entry.statePromise.then(
- (s) => entry.definition.cleanup?.(s),
- () => undefined,
- );
- }
- };
- }, []);
-};