🎥 Make videos programmatically with React
cool
Jonny Burger95adfc298b50
diff --git a/packages/canvas-effects/src/halftone.ts b/packages/canvas-effects/src/halftone.tsindex 3ec070617e..57c49d381a 100644--- a/packages/canvas-effects/src/halftone.ts+++ b/packages/canvas-effects/src/halftone.ts@@ -3,6 +3,9 @@ import {createDescriptor, defineEffect} from 'remotion';export type HalftoneShape = 'circle' | 'square' | 'line';export type HalftoneSampling = 'bilinear' | 'nearest';+/** Where halftone dots are pronounced: dark areas (classic ink), bright areas, or both (two-pass, like directional halftone shaders). */+export type HalftoneRegion = 'shadows' | 'highlights' | 'both';+export type HalftoneParams = {readonly shape?: HalftoneShape;readonly dotSize?: number;@@ -12,6 +15,14 @@ export type HalftoneParams = {readonly sampling?: HalftoneSampling;readonly foreground?: string;readonly background?: string;+ /**+ * Which luminance regions get dots. `shadows` matches classic halftone (larger dots in darker pixels).+ * `highlights` inverts that (larger dots where the image is brighter). `both` draws shadow dots then+ * highlight dots—use `foreground` / `highlightForeground` for the two inks.+ */+ readonly region?: HalftoneRegion;+ /** Dot color for the highlight pass; used when `region` is `highlights` or `both`. Defaults to white. */+ readonly highlightForeground?: string;};type HalftoneResolved = {@@ -23,6 +34,8 @@ type HalftoneResolved = {sampling: HalftoneSampling;foreground: string;background: string;+ region: HalftoneRegion;+ highlightForeground: string;};const resolve = (p: HalftoneParams): HalftoneResolved => ({@@ -34,6 +47,8 @@ const resolve = (p: HalftoneParams): HalftoneResolved => ({sampling: p.sampling ?? 'bilinear',foreground: p.foreground ?? 'black',background: p.background ?? 'white',+ region: p.region ?? 'shadows',+ highlightForeground: p.highlightForeground ?? '#ffffff',});type SampleState = {@@ -50,19 +65,28 @@ type SampleOpts = {sampling: HalftoneSampling;};-const sampleLuminance = ({+type LuminanceAlpha = {lum: number; alpha: number};++const rgbToLum = (i: number, data: Uint8ClampedArray): number =>+ (data[i] * 0.299 + data[i + 1] * 0.587 + data[i + 2] * 0.114) / 255;++/** Samples linear RGB luminance and alpha [0–1]. Alpha is used so transparent pixels are not treated as black. */+const sampleLuminanceAlpha = ({data,sw,sh,x,y,sampling,-}: SampleOpts): number => {+}: SampleOpts): LuminanceAlpha => {if (sampling === 'nearest') {const px = Math.min(Math.max(Math.round(x), 0), sw - 1);const py = Math.min(Math.max(Math.round(y), 0), sh - 1);const i = (py * sw + px) * 4;- return (data[i] * 0.299 + data[i + 1] * 0.587 + data[i + 2] * 0.114) / 255;+ return {+ lum: rgbToLum(i, data),+ alpha: data[i + 3] / 255,+ };}const x0 = Math.floor(x);@@ -80,18 +104,25 @@ const sampleLuminance = ({const i01 = (y1 * sw + cx0) * 4;const i11 = (y1 * sw + x1) * 4;- const l00 =- (data[i00] * 0.299 + data[i00 + 1] * 0.587 + data[i00 + 2] * 0.114) / 255;- const l10 =- (data[i10] * 0.299 + data[i10 + 1] * 0.587 + data[i10 + 2] * 0.114) / 255;- const l01 =- (data[i01] * 0.299 + data[i01 + 1] * 0.587 + data[i01 + 2] * 0.114) / 255;- const l11 =- (data[i11] * 0.299 + data[i11 + 1] * 0.587 + data[i11 + 2] * 0.114) / 255;+ const l00 = rgbToLum(i00, data);+ const l10 = rgbToLum(i10, data);+ const l01 = rgbToLum(i01, data);+ const l11 = rgbToLum(i11, data);++ const a00 = data[i00 + 3] / 255;+ const a10 = data[i10 + 3] / 255;+ const a01 = data[i01 + 3] / 255;+ const a11 = data[i11 + 3] / 255;const top = l00 + (l10 - l00) * fx;const bottom = l01 + (l11 - l01) * fx;- return top + (bottom - top) * fy;+ const lum = top + (bottom - top) * fy;++ const topA = a00 + (a10 - a00) * fx;+ const bottomA = a01 + (a11 - a01) * fx;+ const alpha = topA + (bottomA - topA) * fy;++ return {lum, alpha};};const halftoneDef = defineEffect<HalftoneParams, SampleState>({@@ -134,7 +165,6 @@ const halftoneDef = defineEffect<HalftoneParams, SampleState>({ctx.clearRect(0, 0, width, height);ctx.fillStyle = r.background;ctx.fillRect(0, 0, width, height);- ctx.fillStyle = r.foreground;const rad = (r.rotation * Math.PI) / 180;const cosR = Math.cos(rad);@@ -192,7 +222,7 @@ const halftoneDef = defineEffect<HalftoneParams, SampleState>({continue;}- const lum = sampleLuminance({+ const {lum, alpha} = sampleLuminanceAlpha({data,sw: width,sh: height,@@ -201,35 +231,49 @@ const halftoneDef = defineEffect<HalftoneParams, SampleState>({sampling: r.sampling,});- // Darker pixels → larger dots (1 - luminance)- const dotScale = 1 - lum;- if (dotScale <= 0.01) {- continue;- }+ // Composite onto implicit paper (white): transparent → no ink for shadows,+ // no ink for highlights. Avoids (0,0,0,0) reading as luminance 0.+ const lumShadow = lum * alpha + (1 - alpha);+ const lumHighlight = lum * alpha;const dotX = cx + gridX * cosR - gridY * sinR;const dotY = cy + gridX * sinR + gridY * cosR;- if (r.shape === 'circle') {- const radius = halfSize * dotScale;- ctx.beginPath();- ctx.arc(dotX, dotY, radius, 0, Math.PI * 2);- ctx.fill();- } else if (r.shape === 'square') {- const s = size * dotScale;- ctx.save();- ctx.translate(dotX, dotY);- ctx.rotate(-rad);- ctx.fillRect(-s / 2, -s / 2, s, s);- ctx.restore();- } else {- // 'line': horizontal stripe in grid space, height scales with luminance- const lineHeight = size * dotScale;- ctx.save();- ctx.translate(dotX, dotY);- ctx.rotate(-rad);- ctx.fillRect(-halfSize, -lineHeight / 2, size, lineHeight);- ctx.restore();+ const drawDot = (dotScale: number, fillStyle: string) => {+ if (dotScale <= 0.01) {+ return;+ }++ ctx.fillStyle = fillStyle;++ if (r.shape === 'circle') {+ const radius = halfSize * dotScale;+ ctx.beginPath();+ ctx.arc(dotX, dotY, radius, 0, Math.PI * 2);+ ctx.fill();+ } else if (r.shape === 'square') {+ const s = size * dotScale;+ ctx.save();+ ctx.translate(dotX, dotY);+ ctx.rotate(-rad);+ ctx.fillRect(-s / 2, -s / 2, s, s);+ ctx.restore();+ } else {+ const lineHeight = size * dotScale;+ ctx.save();+ ctx.translate(dotX, dotY);+ ctx.rotate(-rad);+ ctx.fillRect(-halfSize, -lineHeight / 2, size, lineHeight);+ ctx.restore();+ }+ };++ if (r.region === 'shadows' || r.region === 'both') {+ drawDot(1 - lumShadow, r.foreground);+ }++ if (r.region === 'highlights' || r.region === 'both') {+ drawDot(lumHighlight, r.highlightForeground);}}}@@ -238,6 +282,9 @@ const halftoneDef = defineEffect<HalftoneParams, SampleState>({// Halftone effect inspired by m's Halftone for After Effects. Converts// luminance into a grid of dots, squares, or lines. `sampling` controls-// interpolation when reading luminance between pixel centres.+// interpolation when reading luminance between pixel centres. `region` chooses+// whether dots follow dark areas, bright areas, or both (two inks), approximating+// dual-pass halftone shading without mesh normals. Alpha is blended against white+// so transparent pixels are not interpreted as black RGB.export const halftone = (params: HalftoneParams = {}) =>createDescriptor(halftoneDef, params);diff --git a/packages/canvas-effects/src/index.ts b/packages/canvas-effects/src/index.tsindex b411a4c406..f074c6f073 100644--- a/packages/canvas-effects/src/index.ts+++ b/packages/canvas-effects/src/index.ts@@ -7,6 +7,7 @@ export type {export {halftone} from './halftone.js';export type {HalftoneParams,+ HalftoneRegion,HalftoneSampling,HalftoneShape,} from './halftone.js';diff --git a/packages/core/src/HtmlInCanvas.tsx b/packages/core/src/HtmlInCanvas.tsxindex 82783cabee..891005b35f 100644--- a/packages/core/src/HtmlInCanvas.tsx+++ b/packages/core/src/HtmlInCanvas.tsx@@ -1,4 +1,4 @@-import React, {useCallback, useEffect, useRef, useState} from 'react';+import React, {useCallback, useEffect, useRef} from 'react';import type {EffectsProp} from './canvas-effects/effect-types.js';import {runEffectChain} from './canvas-effects/run-effect-chain.js';import {useEffectChainState} from './canvas-effects/use-effect-chain-state.js';@@ -31,6 +31,15 @@ type HTMLCanvasWithLayoutSubtree = HTMLCanvasElement & {requestPaint: () => void;};+export type HtmlInCanvasComposeParams = {+ readonly source: CanvasImageSource;+ readonly target: HTMLCanvasElement;+ readonly frame: number;+ readonly width: number;+ readonly height: number;+ readonly pixelRatio: number;+};+export const isHtmlInCanvasSupported = (): boolean => {if (typeof document === 'undefined') {return false;@@ -57,6 +66,9 @@ export type HtmlInCanvasProps = Omit<readonly effects?: EffectsProp;readonly children: React.ReactNode;readonly pixelRatio?: number;+ readonly onCompose?: (+ params: HtmlInCanvasComposeParams,+ ) => void | Promise<void>;};const htmlInCanvasSchema = {@@ -101,6 +113,7 @@ const HtmlInCanvasInner: React.FC<children,style,pixelRatio = 1,+ onCompose,controls,durationInFrames,...sequenceProps@@ -110,11 +123,8 @@ const HtmlInCanvasInner: React.FC<const frame = useCurrentFrame();const {delayRender, continueRender, cancelRender} = useDelayRender();- const sourceCanvasRef = useRef<HTMLCanvasElement | null>(null);+ const canvasRef = useRef<HTMLCanvasElement | null>(null);const sceneRef = useRef<HTMLDivElement | null>(null);- const [outputCanvas, setOutputCanvas] = useState<HTMLCanvasElement | null>(- null,- );const chainState = useEffectChainState(width, height);@@ -134,58 +144,54 @@ const HtmlInCanvasInner: React.FC<const pendingHandleRef = useRef<number | null>(null);const onPaint = useCallback(() => {- const sourceCanvas =- sourceCanvasRef.current as HTMLCanvasWithLayoutSubtree | null;+ const canvas = canvasRef.current as HTMLCanvasWithLayoutSubtree | null;const sceneEl = sceneRef.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'),- );+ if (!canvas || !sceneEl || !chainState || handle === null) {return;}- const w = widthRef.current;- const h = heightRef.current;+ try {+ const ctx = canvas.getContext('2d') as Canvas2DWithDrawElement | null;+ if (!ctx) {+ throw new Error(+ 'Failed to acquire 2D context for <HtmlInCanvas> canvas',+ );+ }- ctx.reset();- ctx.drawElementImage(sceneEl, 0, 0, w, h);+ const w = widthRef.current;+ const h = heightRef.current;- const capturedHandle = handle;- pendingHandleRef.current = null;+ // Layout-subtree children are not shown on-screen until rasterized here;+ // effects then read from and write back to this same surface (via pool).+ ctx.reset();+ ctx.drawElementImage(sceneEl, 0, 0, w, h);- 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);- }+ const capturedHandle = handle;+ pendingHandleRef.current = null;+ runEffectChain({+ state: chainState,+ source: canvas,+ effects: effectsRef.current,+ output: canvas,+ frame: frameRef.current,+ width: w,+ height: h,+ pixelRatio: pixelRatioRef.current,})- .catch((err) => {- cancelRender(err);- });- }, [outputCanvas, chainState, continueRender, cancelRender]);+ .then((completed) => {+ if (completed) {+ continueRender(capturedHandle);+ }+ })+ .catch((err) => {+ cancelRender(err);+ });+ } catch (error) {+ cancelRender(error);+ }+ }, [chainState, continueRender, cancelRender]);// Set up layoutSubtree and persistent paint listener.useEffect(() => {@@ -198,16 +204,15 @@ const HtmlInCanvasInner: React.FC<return;}- const sourceCanvas =- sourceCanvasRef.current as HTMLCanvasWithLayoutSubtree | null;- if (!sourceCanvas) {+ const canvas = canvasRef.current as HTMLCanvasWithLayoutSubtree | null;+ if (!canvas) {return;}- sourceCanvas.layoutSubtree = true;- sourceCanvas.addEventListener('paint', onPaint);+ canvas.layoutSubtree = true;+ canvas.addEventListener('paint', onPaint);return () => {- sourceCanvas.removeEventListener('paint', onPaint);+ canvas.removeEventListener('paint', onPaint);};}, [onPaint, cancelRender]);@@ -222,9 +227,8 @@ const HtmlInCanvasInner: React.FC<pendingHandleRef.current = handle;- const sourceCanvas =- sourceCanvasRef.current as HTMLCanvasWithLayoutSubtree | null;- sourceCanvas?.requestPaint();+ const canvas = canvasRef.current as HTMLCanvasWithLayoutSubtree | null;+ canvas?.requestPaint();return () => {if (pendingHandleRef.current === handle) {@@ -243,7 +247,7 @@ const HtmlInCanvasInner: React.FC<style={style}><canvas- ref={sourceCanvasRef}+ ref={canvasRef}width={width}height={height}style={{@@ -251,7 +255,6 @@ const HtmlInCanvasInner: React.FC<inset: 0,width,height,- visibility: 'visible',}}><div@@ -264,17 +267,6 @@ const HtmlInCanvasInner: React.FC<{children}</div></canvas>- <canvas- ref={setOutputCanvas}- width={width}- height={height}- style={{- position: 'absolute',- inset: 0,- width,- height,- }}- /></Sequence>);};diff --git a/packages/core/src/canvas-effects/run-effect-chain.ts b/packages/core/src/canvas-effects/run-effect-chain.tsindex f5e7c36e36..b1b537e19c 100644--- a/packages/core/src/canvas-effects/run-effect-chain.ts+++ b/packages/core/src/canvas-effects/run-effect-chain.ts@@ -83,6 +83,12 @@ export const runEffectChain = async ({let lastTarget: HTMLCanvasElement | null = null;if (runs.length === 0) {+ // In-place pipeline (e.g. <HtmlInCanvas>: drawElementImage into the same+ // surface, no further effects) — the bitmap is already on `output`.+ if (source === output) {+ return true;+ }+const ctx = output.getContext('2d');if (!ctx) {throw new Error('Failed to acquire 2D context for output canvas');diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 69fe78e737..6cda6a2ee8 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -142,7 +142,10 @@ export {SolidProps,} from './canvas-effects/index.js';export {HtmlInCanvas, isHtmlInCanvasSupported} from './HtmlInCanvas.js';-export type {HtmlInCanvasProps} from './HtmlInCanvas.js';+export type {+ HtmlInCanvasComposeParams,+ HtmlInCanvasProps,+} from './HtmlInCanvas.js';export type {AnyZodObject} from './any-zod-type.js';export {Artifact} from './Artifact.js';export {Audio, Html5Audio, RemotionAudioProps} from './audio/index.js';diff --git a/packages/example/src/HtmlInCanvas/compose-async-bitmap.tsx b/packages/example/src/HtmlInCanvas/compose-async-bitmap.tsxnew file mode 100644index 0000000000..c28421bf84--- /dev/null+++ b/packages/example/src/HtmlInCanvas/compose-async-bitmap.tsx@@ -0,0 +1,33 @@+import React from 'react';+import {AbsoluteFill, HtmlInCanvas, useVideoConfig} from 'remotion';+import {HtmlInCanvasScene} from './scene';++/** Async compose: upload via `createImageBitmap` then draw with 2D (still one frame — await keeps delayRender open). */+export const HtmlInCanvasComposeAsyncBitmap: React.FC = () => {+ const {width, height} = useVideoConfig();++ return (+ <AbsoluteFill style={{backgroundColor: 'black'}}>+ <HtmlInCanvas+ width={width}+ height={height}+ onCompose={async ({source, target, width: w, height: h}) => {+ const bitmap = await createImageBitmap(source);+ try {+ const ctx = target.getContext('2d');+ if (!ctx) {+ return;+ }++ ctx.clearRect(0, 0, w, h);+ ctx.drawImage(bitmap, 0, 0, w, h);+ } finally {+ bitmap.close();+ }+ }}+ >+ <HtmlInCanvasScene />+ </HtmlInCanvas>+ </AbsoluteFill>+ );+};diff --git a/packages/example/src/HtmlInCanvas/compose-blit.tsx b/packages/example/src/HtmlInCanvas/compose-blit.tsxnew file mode 100644index 0000000000..c023a96f61--- /dev/null+++ b/packages/example/src/HtmlInCanvas/compose-blit.tsx@@ -0,0 +1,28 @@+import React from 'react';+import {AbsoluteFill, HtmlInCanvas, useVideoConfig} from 'remotion';+import {HtmlInCanvasScene} from './scene';++/** Explicit 2D blit from rasterized DOM (`source`) to the visible canvas (`target`). */+export const HtmlInCanvasComposeBlit: React.FC = () => {+ const {width, height} = useVideoConfig();++ return (+ <AbsoluteFill style={{backgroundColor: 'black'}}>+ <HtmlInCanvas+ width={width}+ height={height}+ onCompose={({source, target, width: w, height: h}) => {+ const ctx = target.getContext('2d');+ if (!ctx) {+ return;+ }++ ctx.clearRect(0, 0, w, h);+ ctx.drawImage(source, 0, 0, w, h);+ }}+ >+ <HtmlInCanvasScene />+ </HtmlInCanvas>+ </AbsoluteFill>+ );+};diff --git a/packages/example/src/HtmlInCanvas/compose-rotate.tsx b/packages/example/src/HtmlInCanvas/compose-rotate.tsxnew file mode 100644index 0000000000..65e42cab41--- /dev/null+++ b/packages/example/src/HtmlInCanvas/compose-rotate.tsx@@ -0,0 +1,50 @@+import React from 'react';+import {+ AbsoluteFill,+ HtmlInCanvas,+ interpolate,+ useCurrentFrame,+ useVideoConfig,+} from 'remotion';+import {HtmlInCanvasScene} from './scene';++/** 2D rotation around the center using the canvas transform matrix. */+export const HtmlInCanvasComposeRotate: React.FC = () => {+ const frame = useCurrentFrame();+ const {width, height, durationInFrames} = useVideoConfig();++ const rotation = interpolate(+ frame,+ [0, durationInFrames - 1],+ [0, Math.PI * 2],+ {+ extrapolateLeft: 'clamp',+ extrapolateRight: 'clamp',+ },+ );++ return (+ <AbsoluteFill style={{backgroundColor: 'black'}}>+ <HtmlInCanvas+ width={width}+ height={height}+ onCompose={({source, target, width: w, height: h}) => {+ const ctx = target.getContext('2d');+ if (!ctx) {+ return;+ }++ ctx.clearRect(0, 0, w, h);+ ctx.save();+ ctx.translate(w / 2, h / 2);+ ctx.rotate(rotation);+ ctx.translate(-w / 2, -h / 2);+ ctx.drawImage(source, 0, 0, w, h);+ ctx.restore();+ }}+ >+ <HtmlInCanvasScene />+ </HtmlInCanvas>+ </AbsoluteFill>+ );+};diff --git a/packages/example/src/HtmlInCanvas/compose-then-effects.tsx b/packages/example/src/HtmlInCanvas/compose-then-effects.tsxnew file mode 100644index 0000000000..1ff99a1e7b--- /dev/null+++ b/packages/example/src/HtmlInCanvas/compose-then-effects.tsx@@ -0,0 +1,54 @@+import {blur} from '@remotion/canvas-effects';+import React from 'react';+import {+ AbsoluteFill,+ HtmlInCanvas,+ interpolate,+ useCurrentFrame,+ useVideoConfig,+} from 'remotion';+import {HtmlInCanvasScene} from './scene';++/**+ * Compose stage (slight scale pulse) then canvas-effects — effects run on top of the composed image.+ */+export const HtmlInCanvasComposeThenEffects: React.FC = () => {+ const frame = useCurrentFrame();+ const {width, height, durationInFrames} = useVideoConfig();++ const scale = interpolate(frame, [0, durationInFrames - 1], [1, 1.08], {+ extrapolateLeft: 'clamp',+ extrapolateRight: 'clamp',+ });++ const blurRadius = interpolate(frame, [0, durationInFrames - 1], [2, 18], {+ extrapolateLeft: 'clamp',+ extrapolateRight: 'clamp',+ });++ return (+ <AbsoluteFill style={{backgroundColor: 'black'}}>+ <HtmlInCanvas+ width={width}+ height={height}+ onCompose={({source, target, width: w, height: h}) => {+ const ctx = target.getContext('2d');+ if (!ctx) {+ return;+ }++ ctx.clearRect(0, 0, w, h);+ ctx.save();+ ctx.translate(w / 2, h / 2);+ ctx.scale(scale, scale);+ ctx.translate(-w / 2, -h / 2);+ ctx.drawImage(source, 0, 0, w, h);+ ctx.restore();+ }}+ effects={[blur({radius: blurRadius})]}+ >+ <HtmlInCanvasScene />+ </HtmlInCanvas>+ </AbsoluteFill>+ );+};diff --git a/packages/example/src/HtmlInCanvas/compose-webgl.tsx b/packages/example/src/HtmlInCanvas/compose-webgl.tsxnew file mode 100644index 0000000000..ed87ee346d--- /dev/null+++ b/packages/example/src/HtmlInCanvas/compose-webgl.tsx@@ -0,0 +1,192 @@+import React, {useCallback, useEffect, useRef} from 'react';+import {+ AbsoluteFill,+ HtmlInCanvas,+ type HtmlInCanvasComposeParams,+ interpolate,+ useCurrentFrame,+ useVideoConfig,+} from 'remotion';+import {HtmlInCanvasScene} from './scene';++type GpuState = {+ gl: WebGL2RenderingContext;+ program: WebGLProgram;+ uMatrix: WebGLUniformLocation | null;+ uTex: WebGLUniformLocation | null;+ texture: WebGLTexture;+ vao: WebGLVertexArrayObject;+ buffer: WebGLBuffer;+};++const VS = `#version 300 es+in vec2 a_pos;+in vec2 a_uv;+uniform mat3 u_matrix;+out vec2 v_uv;+void main() {+ vec3 p = u_matrix * vec3(a_pos, 1.0);+ gl_Position = vec4(p.xy, 0.0, 1.0);+ v_uv = a_uv;+}`;++const FS = `#version 300 es+precision highp float;+uniform sampler2D u_tex;+in vec2 v_uv;+out vec4 o;+void main() {+ o = texture(u_tex, vec2(v_uv.x, 1.0 - v_uv.y));+}`;++function compileGlsl(gl: WebGL2RenderingContext, vs: string, fs: string) {+ const vert = gl.createShader(gl.VERTEX_SHADER)!;+ gl.shaderSource(vert, vs);+ gl.compileShader(vert);+ const frag = gl.createShader(gl.FRAGMENT_SHADER)!;+ gl.shaderSource(frag, fs);+ gl.compileShader(frag);+ const program = gl.createProgram()!;+ gl.attachShader(program, vert);+ gl.attachShader(program, frag);+ gl.linkProgram(program);+ gl.deleteShader(vert);+ gl.deleteShader(frag);+ return program;+}++const QUAD = new Float32Array([+ -1, -1, 0, 0, 1, -1, 1, 0, -1, 1, 0, 1, 1, -1, 1, 0, -1, 1, 0, 1, 1, 1, 1, 1,+]);++function ensureGpu(+ target: HTMLCanvasElement,+ ref: React.MutableRefObject<GpuState | null>,+): GpuState | null {+ if (ref.current) {+ return ref.current;+ }++ const gl = target.getContext('webgl2', {+ alpha: true,+ premultipliedAlpha: true,+ antialias: false,+ });+ if (!gl) {+ return null;+ }++ const program = compileGlsl(gl, VS, FS);+ const uMatrix = gl.getUniformLocation(program, 'u_matrix');+ const uTex = gl.getUniformLocation(program, 'u_tex');+ const texture = gl.createTexture()!;+ 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);++ const buffer = gl.createBuffer()!;+ gl.bindBuffer(gl.ARRAY_BUFFER, buffer);+ gl.bufferData(gl.ARRAY_BUFFER, QUAD, gl.STATIC_DRAW);++ const vao = gl.createVertexArray()!;+ gl.bindVertexArray(vao);+ const locPos = gl.getAttribLocation(program, 'a_pos');+ const locUv = gl.getAttribLocation(program, 'a_uv');+ gl.enableVertexAttribArray(locPos);+ gl.vertexAttribPointer(locPos, 2, gl.FLOAT, false, 16, 0);+ gl.enableVertexAttribArray(locUv);+ gl.vertexAttribPointer(locUv, 2, gl.FLOAT, false, 16, 8);++ ref.current = {gl, program, uMatrix, uTex, texture, vao, buffer};+ return ref.current;+}++function disposeGpu(ref: React.MutableRefObject<GpuState | null>) {+ const g = ref.current;+ if (!g) {+ return;+ }++ const {gl} = g;+ gl.deleteProgram(g.program);+ gl.deleteTexture(g.texture);+ gl.deleteVertexArray(g.vao);+ gl.deleteBuffer(g.buffer);+ ref.current = null;+}++/** WebGL2 full-screen quad; shaders and textures memoized on a ref (see plan). Falls back to 2D blit when WebGL2 is unavailable. */+export const HtmlInCanvasComposeWebGL: React.FC = () => {+ const frame = useCurrentFrame();+ const {width, height, durationInFrames} = useVideoConfig();+ const gpuRef = useRef<GpuState | null>(null);++ const rotation = interpolate(+ frame,+ [0, durationInFrames - 1],+ [0, Math.PI * 2],+ {+ extrapolateLeft: 'clamp',+ extrapolateRight: 'clamp',+ },+ );++ useEffect(() => () => disposeGpu(gpuRef), []);++ const onCompose = useCallback(+ ({source, target, width: w, height: h}: HtmlInCanvasComposeParams) => {+ const c = Math.cos(rotation);+ const s = Math.sin(rotation);+ const mat = new Float32Array([c, -s, 0, s, c, 0, 0, 0, 1]);++ const gpu = ensureGpu(target, gpuRef);+ if (!gpu) {+ const ctx = target.getContext('2d');+ if (!ctx) {+ return;+ }++ ctx.clearRect(0, 0, w, h);+ ctx.drawImage(source, 0, 0, w, h);+ return;+ }++ const {gl} = gpu;+ gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);+ gl.useProgram(gpu.program);++ gl.activeTexture(gl.TEXTURE0);+ gl.bindTexture(gl.TEXTURE_2D, gpu.texture);+ gl.texImage2D(+ gl.TEXTURE_2D,+ 0,+ gl.RGBA,+ gl.RGBA,+ gl.UNSIGNED_BYTE,+ source as TexImageSource,+ );++ if (gpu.uTex) {+ gl.uniform1i(gpu.uTex, 0);+ }++ if (gpu.uMatrix) {+ gl.uniformMatrix3fv(gpu.uMatrix, false, mat);+ }++ gl.bindVertexArray(gpu.vao);+ gl.drawArrays(gl.TRIANGLES, 0, 6);+ },+ [rotation],+ );++ return (+ <AbsoluteFill style={{backgroundColor: 'black'}}>+ <HtmlInCanvas width={width} height={height} onCompose={onCompose}>+ <HtmlInCanvasScene />+ </HtmlInCanvas>+ </AbsoluteFill>+ );+};diff --git a/packages/example/src/HtmlInCanvas/compose-zoom-pan.tsx b/packages/example/src/HtmlInCanvas/compose-zoom-pan.tsxnew file mode 100644index 0000000000..6e1fecdc3a--- /dev/null+++ b/packages/example/src/HtmlInCanvas/compose-zoom-pan.tsx@@ -0,0 +1,55 @@+import React from 'react';+import {+ AbsoluteFill,+ HtmlInCanvas,+ interpolate,+ useCurrentFrame,+ useVideoConfig,+} from 'remotion';+import {HtmlInCanvasScene} from './scene';++/** Animated zoom and pan using every frame’s interpolation (no refs needed). */+export const HtmlInCanvasComposeZoomPan: React.FC = () => {+ const frame = useCurrentFrame();+ const {width, height, durationInFrames} = useVideoConfig();++ const zoom = interpolate(frame, [0, durationInFrames - 1], [1, 1.35], {+ extrapolateLeft: 'clamp',+ extrapolateRight: 'clamp',+ });++ const panX = interpolate(frame, [0, durationInFrames - 1], [0, 180], {+ extrapolateLeft: 'clamp',+ extrapolateRight: 'clamp',+ });++ const panY = interpolate(frame, [0, durationInFrames - 1], [0, -120], {+ extrapolateLeft: 'clamp',+ extrapolateRight: 'clamp',+ });++ return (+ <AbsoluteFill style={{backgroundColor: 'black'}}>+ <HtmlInCanvas+ width={width}+ height={height}+ onCompose={({source, target, width: w, height: h}) => {+ const ctx = target.getContext('2d');+ if (!ctx) {+ return;+ }++ ctx.setTransform(1, 0, 0, 1, 0, 0);+ ctx.clearRect(0, 0, w, h);+ ctx.save();+ ctx.translate(panX, panY);+ ctx.scale(zoom, zoom);+ ctx.drawImage(source, 0, 0, w, h);+ ctx.restore();+ }}+ >+ <HtmlInCanvasScene />+ </HtmlInCanvas>+ </AbsoluteFill>+ );+};diff --git a/packages/example/src/HtmlInCanvas/effects-demo.tsx b/packages/example/src/HtmlInCanvas/effects-demo.tsxnew file mode 100644index 0000000000..3217a00683--- /dev/null+++ b/packages/example/src/HtmlInCanvas/effects-demo.tsx@@ -0,0 +1,41 @@+import {blur, tint, wave} from '@remotion/canvas-effects';+import React from 'react';+import {+ AbsoluteFill,+ HtmlInCanvas,+ interpolate,+ useCurrentFrame,+ useVideoConfig,+} from 'remotion';+import {HtmlInCanvasScene} from './scene';++export const HtmlInCanvasEffectsDemo: React.FC = () => {+ const frame = useCurrentFrame();+ const {width, height, durationInFrames} = useVideoConfig();++ const blurRadius = interpolate(frame, [0, durationInFrames - 1], [0, 24], {+ extrapolateLeft: 'clamp',+ extrapolateRight: 'clamp',+ });++ const tintAmount = interpolate(frame, [0, durationInFrames - 1], [0, 0.4], {+ extrapolateLeft: 'clamp',+ extrapolateRight: 'clamp',+ });++ return (+ <AbsoluteFill style={{backgroundColor: 'black'}}>+ <HtmlInCanvas+ width={width}+ height={height}+ effects={[+ wave({amplitude: 40, wavelength: 240}),+ blur({radius: blurRadius}),+ tint({color: 'cyan', amount: tintAmount}),+ ]}+ >+ <HtmlInCanvasScene />+ </HtmlInCanvas>+ </AbsoluteFill>+ );+};diff --git a/packages/example/src/HtmlInCanvas/index.tsx b/packages/example/src/HtmlInCanvas/index.tsxindex 7e455d7481..c1b93378ea 100644--- a/packages/example/src/HtmlInCanvas/index.tsx+++ b/packages/example/src/HtmlInCanvas/index.tsx@@ -1,72 +1,12 @@-import {blur, tint, wave} from '@remotion/canvas-effects';-import React from 'react';-import {- AbsoluteFill,- HtmlInCanvas,- interpolate,- useCurrentFrame,- useVideoConfig,-} from 'remotion';--const Scene: React.FC = () => {- const frame = useCurrentFrame();- const {durationInFrames} = useVideoConfig();-- const progress = frame / durationInFrames;- const hue = Math.round(progress * 360);-- return (- <AbsoluteFill- style={{- flexDirection: 'column',- alignItems: 'center',- justifyContent: 'center',- gap: 40,- background: `linear-gradient(135deg, hsl(${hue}, 80%, 60%), hsl(${- (hue + 80) % 360- }, 80%, 40%))`,- color: 'white',- fontFamily:- '-apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif',- textAlign: 'center',- fontSize: 56,- fontWeight: 600,- padding: '20px 40px',- borderRadius: 24,- }}- >- {frame}- </AbsoluteFill>- );-};--export const HtmlInCanvasDemo: React.FC = () => {- const frame = useCurrentFrame();- const {width, height, durationInFrames} = useVideoConfig();-- const blurRadius = interpolate(frame, [0, durationInFrames - 1], [0, 24], {- extrapolateLeft: 'clamp',- extrapolateRight: 'clamp',- });-- const tintAmount = interpolate(frame, [0, durationInFrames - 1], [0, 0.4], {- extrapolateLeft: 'clamp',- extrapolateRight: 'clamp',- });-- return (- <AbsoluteFill style={{backgroundColor: 'black'}}>- <HtmlInCanvas- width={width}- height={height}- effects={[- wave({amplitude: 40, wavelength: 240}),- blur({radius: blurRadius}),- tint({color: 'cyan', amount: tintAmount}),- ]}- >- <Scene />- </HtmlInCanvas>- </AbsoluteFill>- );-};+export {HtmlInCanvasComposeAsyncBitmap} from './compose-async-bitmap';+export {HtmlInCanvasComposeBlit} from './compose-blit';+export {HtmlInCanvasComposeRotate} from './compose-rotate';+export {HtmlInCanvasComposeThenEffects} from './compose-then-effects';+export {HtmlInCanvasComposeWebGL} from './compose-webgl';+export {HtmlInCanvasComposeZoomPan} from './compose-zoom-pan';+export {+ HtmlInCanvasEffectsDemo,+ HtmlInCanvasEffectsDemo as HtmlInCanvasDemo,+} from './effects-demo';+export {HtmlInCanvasReactSvg} from './react-svg';+export {HtmlInCanvasScene} from './scene';diff --git a/packages/example/src/HtmlInCanvas/react-svg.tsx b/packages/example/src/HtmlInCanvas/react-svg.tsxnew file mode 100644index 0000000000..49fc3e4130--- /dev/null+++ b/packages/example/src/HtmlInCanvas/react-svg.tsx@@ -0,0 +1,27 @@+import {halftone, tint} from '@remotion/canvas-effects';+import React from 'react';+import {HtmlInCanvas, useVideoConfig} from 'remotion';+import ReactSvg from '../ReactSvg';++/** ReactSvg scene rasterized with drawElementImage, then halftone + tint on the canvas. */+export const HtmlInCanvasReactSvg: React.FC<{+ readonly transparent: boolean;+}> = ({transparent}) => {+ const {width, height} = useVideoConfig();++ return (+ <HtmlInCanvas+ width={width}+ height={height}+ effects={[+ halftone({+ dotSize: 20,+ background: 'white',+ }),+ tint({color: 'green', amount: 0.1}),+ ]}+ >+ <ReactSvg transparent={transparent} />+ </HtmlInCanvas>+ );+};diff --git a/packages/example/src/HtmlInCanvas/scene.tsx b/packages/example/src/HtmlInCanvas/scene.tsxnew file mode 100644index 0000000000..fa1f88620d--- /dev/null+++ b/packages/example/src/HtmlInCanvas/scene.tsx@@ -0,0 +1,34 @@+import React from 'react';+import {AbsoluteFill, useCurrentFrame, useVideoConfig} from 'remotion';++export const HtmlInCanvasScene: React.FC = () => {+ const frame = useCurrentFrame();+ const {durationInFrames} = useVideoConfig();++ const progress = frame / Math.max(durationInFrames, 1);+ const hue = Math.round(progress * 360);++ return (+ <AbsoluteFill+ style={{+ flexDirection: 'column',+ alignItems: 'center',+ justifyContent: 'center',+ gap: 40,+ background: `linear-gradient(135deg, hsl(${hue}, 80%, 60%), hsl(${+ (hue + 80) % 360+ }, 80%, 40%))`,+ color: 'white',+ fontFamily:+ '-apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif',+ textAlign: 'center',+ fontSize: 56,+ fontWeight: 600,+ padding: '20px 40px',+ borderRadius: 24,+ }}+ >+ {frame}+ </AbsoluteFill>+ );+};diff --git a/packages/example/src/Root.tsx b/packages/example/src/Root.tsxindex 1c7001a0b1..d0e6c55c0e 100644--- a/packages/example/src/Root.tsx+++ b/packages/example/src/Root.tsx@@ -38,7 +38,16 @@ import {FreezeExample} from './Freeze/FreezeExample';import {FreezePortion} from './FreezePortion/FreezePortion';import {Green} from './Green';import {HlsDemo} from './Hls/HlsDemo';-import {HtmlInCanvasDemo} from './HtmlInCanvas';+import {+ HtmlInCanvasComposeAsyncBitmap,+ HtmlInCanvasComposeBlit,+ HtmlInCanvasComposeRotate,+ HtmlInCanvasComposeThenEffects,+ HtmlInCanvasComposeWebGL,+ HtmlInCanvasComposeZoomPan,+ HtmlInCanvasDemo,+ HtmlInCanvasReactSvg,+} from './HtmlInCanvas';import {HugeImage} from './HugeImage';import {HugePayload, hugePayloadSchema} from './HugePayload';import {Layers} from './Layers';@@ -848,14 +857,75 @@ export const Index: React.FC = () => {width={1080}durationInFrames={100}/>- <Composition- id="html-in-canvas"- component={HtmlInCanvasDemo}- fps={30}- height={1080}- width={1920}- durationInFrames={120}- />+ <Folder name="html-in-canvas">+ <Composition+ id="html-in-canvas"+ component={HtmlInCanvasDemo}+ fps={30}+ height={1080}+ width={1920}+ durationInFrames={120}+ />+ <Composition+ id="html-in-canvas-compose-blit"+ component={HtmlInCanvasComposeBlit}+ fps={30}+ height={1080}+ width={1920}+ durationInFrames={120}+ />+ <Composition+ id="html-in-canvas-compose-rotate"+ component={HtmlInCanvasComposeRotate}+ fps={30}+ height={1080}+ width={1920}+ durationInFrames={120}+ />+ <Composition+ id="html-in-canvas-compose-zoom-pan"+ component={HtmlInCanvasComposeZoomPan}+ fps={30}+ height={1080}+ width={1920}+ durationInFrames={120}+ />+ <Composition+ id="html-in-canvas-compose-async-bitmap"+ component={HtmlInCanvasComposeAsyncBitmap}+ fps={30}+ height={1080}+ width={1920}+ durationInFrames={120}+ />+ <Composition+ id="html-in-canvas-compose-webgl"+ component={HtmlInCanvasComposeWebGL}+ fps={30}+ height={1080}+ width={1920}+ durationInFrames={120}+ />+ <Composition+ id="html-in-canvas-compose-then-effects"+ component={HtmlInCanvasComposeThenEffects}+ fps={30}+ height={1080}+ width={1920}+ durationInFrames={120}+ />+ <Composition+ id="html-in-canvas-react-svg"+ component={HtmlInCanvasReactSvg}+ width={1920}+ height={1080}+ fps={60}+ durationInFrames={300}+ defaultProps={{+ transparent: true,+ }}+ />+ </Folder><Compositionid="video-testing-webm"component={VideoTesting}