🎥 Make videos programmatically with React
simplify
Jonny Burgerb11fa44b6084
diff --git a/packages/core/src/HtmlInCanvas.tsx b/packages/core/src/HtmlInCanvas.tsxindex 55c5af8dea..48afe90fa2 100644--- a/packages/core/src/HtmlInCanvas.tsx+++ b/packages/core/src/HtmlInCanvas.tsx@@ -164,7 +164,6 @@ declare global {export type HtmlInCanvasComposeParams = {readonly canvas: HTMLCanvasElement;- readonly frame: number;readonly width: number;readonly height: number;readonly element: HTMLDivElement;@@ -251,7 +250,7 @@ const HtmlInCanvasInner: React.FC<const {continueRender, cancelRender} = useDelayRender();const canvasRef = useRef<HTMLCanvasElement | null>(null);- const sceneRef = useRef<HTMLDivElement | null>(null);+ const divRef = useRef<HTMLDivElement | null>(null);const chainState = useEffectChainState(canvasRef.current?.width ?? 0,@@ -268,20 +267,19 @@ const HtmlInCanvasInner: React.FC<const onPaintCb = useCallback(async () => {const canvas = canvasRef.current;- const sceneEl = sceneRef.current;+ const element = divRef.current;- if (!canvas || !sceneEl) {+ if (!canvas || !element) {throw new Error('Canvas or scene element not found');}try {const handle = delayRender('onPaint');await onPaintRef.current?.({- frame: frameRef.current,canvas,width: canvas.width,height: canvas.height,- element: sceneEl,+ element,});if (!ENABLE_EFFECTS) {@@ -289,12 +287,12 @@ const HtmlInCanvasInner: React.FC<return;}- if (!chainState) {- return;+ if (!chainState?.current) {+ throw new Error('Effect chain state not found');}const completed = await runEffectChain({- state: chainState,+ state: chainState.current!,source: canvas,effects: effectsRef.current,output: canvas,@@ -329,6 +327,7 @@ const HtmlInCanvasInner: React.FC<canvas.layoutSubtree = true;canvas.addEventListener('paint', onPaintCb);+return () => {canvas.removeEventListener('paint', onPaintCb);};@@ -346,12 +345,11 @@ const HtmlInCanvasInner: React.FC<durationInFrames={resolvedDuration}name="<HtmlInCanvas>"controls={controls}- width={width}- height={height}+ layout="none"{...sequenceProps}><canvas ref={canvasRef} width={width} height={height} style={style}>- <div ref={sceneRef} style={innerStyle}>+ <div ref={divRef} style={innerStyle}>{children}</div></canvas>diff --git a/packages/core/src/canvas-effects/Solid.tsx b/packages/core/src/canvas-effects/Solid.tsxindex 3dd4407a01..5e4b95a8c8 100644--- a/packages/core/src/canvas-effects/Solid.tsx+++ b/packages/core/src/canvas-effects/Solid.tsx@@ -89,7 +89,7 @@ export const Solid: React.FC<SolidProps> = ({ctx.fillRect(0, 0, 1, 1);runEffectChain({- state: chainState,+ state: chainState.current!,source: sourceCanvas,effects: experimentalEffects,output: outputCanvas,diff --git a/packages/core/src/canvas-effects/use-effect-chain-state.ts b/packages/core/src/canvas-effects/use-effect-chain-state.tsindex b6b4c7b6e7..2d03f9e5b3 100644--- a/packages/core/src/canvas-effects/use-effect-chain-state.ts+++ b/packages/core/src/canvas-effects/use-effect-chain-state.ts@@ -1,3 +1,4 @@+import type {RefObject} from 'react';import {useEffect, useRef} from 'react';import {ENABLE_EFFECTS} from '../enable-effects.js';import type {EffectChainState} from './run-effect-chain.js';@@ -9,7 +10,7 @@ import {export const useEffectChainState = (width: number,height: number,-): EffectChainState | null => {+): RefObject<EffectChainState | null> | null => {const chainStateRef = useRef<EffectChainState | null>(null);const sizeRef = useRef<{width: number; height: number} | null>(null);@@ -44,5 +45,5 @@ export const useEffectChainState = (return null;}- return chainStateRef.current;+ return chainStateRef;};diff --git a/packages/example/src/HtmlInCanvas/compose-async-bitmap.tsx b/packages/example/src/HtmlInCanvas/compose-async-bitmap.tsxindex 26a3709f94..f771bae29f 100644--- a/packages/example/src/HtmlInCanvas/compose-async-bitmap.tsx+++ b/packages/example/src/HtmlInCanvas/compose-async-bitmap.tsx@@ -11,10 +11,10 @@ export const HtmlInCanvasComposeAsyncBitmap: React.FC = () => {<HtmlInCanvaswidth={width}height={height}- onPaint={async ({canvas: source, target, width: w, height: h}) => {+ onPaint={async ({canvas: source, width: w, height: h}) => {const bitmap = await createImageBitmap(source);try {- const ctx = target.getContext('2d');+ const ctx = source.getContext('2d');if (!ctx) {return;}diff --git a/packages/example/src/HtmlInCanvas/compose-blit.tsx b/packages/example/src/HtmlInCanvas/compose-blit.tsxdeleted file mode 100644index 930e149b3b..0000000000--- a/packages/example/src/HtmlInCanvas/compose-blit.tsx+++ /dev/null@@ -1,28 +0,0 @@-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}- onPaint={({canvas: 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.tsxdeleted file mode 100644index fc1a30d6c2..0000000000--- a/packages/example/src/HtmlInCanvas/compose-rotate.tsx+++ /dev/null@@ -1,50 +0,0 @@-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}- onPaint={({canvas: 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-zoom-pan.tsx b/packages/example/src/HtmlInCanvas/compose-zoom-pan.tsxdeleted file mode 100644index 2bb42eb93d..0000000000--- a/packages/example/src/HtmlInCanvas/compose-zoom-pan.tsx+++ /dev/null@@ -1,55 +0,0 @@-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}- onPaint={({canvas: 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.tsxindex 872cc0c547..5046e72640 100644--- a/packages/example/src/HtmlInCanvas/effects-demo.tsx+++ b/packages/example/src/HtmlInCanvas/effects-demo.tsx@@ -2,46 +2,121 @@ import React from 'react';import {AbsoluteFill,HtmlInCanvas,- spring,+ interpolate,useCurrentFrame,- useVideoConfig,} from 'remotion';import {HtmlInCanvasScene} from './scene';export const HtmlInCanvasEffectsDemo: React.FC = () => {- const {width, height} = useVideoConfig();+ const frame = useCurrentFrame();+ // Animate the halftone cell size — small dots → big dots over the comp.+ const cellSize = 6;- const scale = spring({- frame: useCurrentFrame(),- fps: useVideoConfig().fps,- config: {- damping: 10,- stiffness: 100,- },- });+ const size = interpolate(frame, [0, 100], [400, 1000]);return (- <AbsoluteFill>+ <AbsoluteFill style={{justifyContent: 'center', alignItems: 'center'}}><HtmlInCanvas- width={width}- height={height}- style={{scale}}- onPaint={({canvas, element}) => {- const ctx = canvas.getContext('2d');+ width={size}+ height={size}+ onPaint={({canvas, element, width: w, height: h}) => {+ const ctx = canvas.getContext('2d', {willReadFrequently: true});if (!ctx) {throw new Error('Failed to acquire 2D context for <HtmlInCanvas> canvas',);}+ // 1. Rasterize DOM subtree, then read pixels back. This step is+ // what makes the effect impossible in pure HTML/CSS — we need+ // actual sampled pixel data from the rendered subtree.ctx.reset();- ctx.rotate((15 * Math.PI) / 180);- ctx.translate(80 * devicePixelRatio, -20 * devicePixelRatio);- const transform = ctx.drawElementImage(element, 0, 0);+ const transform = ctx.drawElementImage(element, 0, 0, w, h);element.style.transform = transform.toString();+ const {data: pixels} = ctx.getImageData(0, 0, w, h);++ // 2. Repaint as a halftone dot grid with per-channel offsets:+ // each cell samples a region's average color, then draws three+ // overlapping circles (R/G/B) at slightly different positions.+ // Radius scales inversely with luminance — dark = big dot.+ ctx.reset();++ const cell = Math.max(2, Math.round(cellSize));+ const maxR = (cell / 2) * Math.SQRT2;+ const offset = cell * 0.18;++ ctx.globalCompositeOperation = 'lighter';++ for (let y = 0; y < h; y += cell) {+ for (let x = 0; x < w; x += cell) {+ let r = 0;+ let g = 0;+ let b = 0;+ let a = 0;+ let count = 0;++ const yEnd = Math.min(y + cell, h);+ const xEnd = Math.min(x + cell, w);+ for (let py = y; py < yEnd; py += 2) {+ for (let px = x; px < xEnd; px += 2) {+ const i = (py * w + px) * 4;+ r += pixels[i];+ g += pixels[i + 1];+ b += pixels[i + 2];+ a += pixels[i + 3];+ count++;+ }+ }++ if (count === 0 || a / count < 8) {+ continue;+ }++ const avgR = r / count;+ const avgG = g / count;+ const avgB = b / count;+ const luminance =+ (0.2126 * avgR + 0.7152 * avgG + 0.0722 * avgB) / 255;++ const radius = maxR * (1 - luminance);+ if (radius < 0.4) {+ continue;+ }++ const cx = x + cell / 2;+ const cy = y + cell / 2;++ ctx.fillStyle = `rgb(${avgR.toFixed(0)}, 0, 0)`;+ ctx.beginPath();+ ctx.arc(cx - offset, cy, radius, 0, Math.PI * 2);+ ctx.fill();++ ctx.fillStyle = `rgb(0, ${avgG.toFixed(0)}, 0)`;+ ctx.beginPath();+ ctx.arc(cx + offset, cy - offset, radius, 0, Math.PI * 2);+ ctx.fill();++ ctx.fillStyle = `rgb(0, 0, ${avgB.toFixed(0)})`;+ ctx.beginPath();+ ctx.arc(cx + offset, cy + offset, radius, 0, Math.PI * 2);+ ctx.fill();+ }+ }++ ctx.globalCompositeOperation = 'source-over';}}>- <HtmlInCanvasScene />+ <div+ style={{+ width: size,+ height: size,+ backgroundColor: '#101728',+ justifyContent: 'center',+ alignItems: 'center',+ }}+ >+ <HtmlInCanvasScene />+ </div></HtmlInCanvas></AbsoluteFill>);diff --git a/packages/example/src/HtmlInCanvas/index.tsx b/packages/example/src/HtmlInCanvas/index.tsxindex c1b93378ea..3b3ab6c294 100644--- a/packages/example/src/HtmlInCanvas/index.tsx+++ b/packages/example/src/HtmlInCanvas/index.tsx@@ -1,9 +1,6 @@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,diff --git a/packages/example/src/HtmlInCanvas/scene.tsx b/packages/example/src/HtmlInCanvas/scene.tsxindex 947a7d9a4b..bd3d9c3468 100644--- a/packages/example/src/HtmlInCanvas/scene.tsx+++ b/packages/example/src/HtmlInCanvas/scene.tsx@@ -1,11 +1,11 @@import React from 'react';-import {AbsoluteFill, useCurrentFrame} from 'remotion';+import {useCurrentFrame} from 'remotion';export const HtmlInCanvasScene: React.FC = () => {const frame = useCurrentFrame();return (- <AbsoluteFill+ <divstyle={{flexDirection: 'column',alignItems: 'center',@@ -22,6 +22,6 @@ export const HtmlInCanvasScene: React.FC = () => {}}>Hello World {frame}- </AbsoluteFill>+ </div>);};diff --git a/packages/example/src/Root.tsx b/packages/example/src/Root.tsxindex d0e6c55c0e..fc12c06f65 100644--- a/packages/example/src/Root.tsx+++ b/packages/example/src/Root.tsx@@ -40,11 +40,8 @@ import {Green} from './Green';import {HlsDemo} from './Hls/HlsDemo';import {HtmlInCanvasComposeAsyncBitmap,- HtmlInCanvasComposeBlit,- HtmlInCanvasComposeRotate,HtmlInCanvasComposeThenEffects,HtmlInCanvasComposeWebGL,- HtmlInCanvasComposeZoomPan,HtmlInCanvasDemo,HtmlInCanvasReactSvg,} from './HtmlInCanvas';@@ -866,30 +863,6 @@ export const Index: React.FC = () => {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}- /><Compositionid="html-in-canvas-compose-async-bitmap"component={HtmlInCanvasComposeAsyncBitmap}diff --git a/packages/media/src/video-iterator-manager.ts b/packages/media/src/video-iterator-manager.tsindex 26560b40b6..9fcaddfee9 100644--- a/packages/media/src/video-iterator-manager.ts+++ b/packages/media/src/video-iterator-manager.ts@@ -83,7 +83,6 @@ export const videoIteratorManager = ({frame: getCurrentFrame(),width: canvas.width,height: canvas.height,- pixelRatio: 1,});} else {context.clearRect(0, 0, canvas.width, canvas.height);diff --git a/packages/media/src/video/video-for-preview.tsx b/packages/media/src/video/video-for-preview.tsxindex f16bc0f43c..34d01e441e 100644--- a/packages/media/src/video/video-for-preview.tsx+++ b/packages/media/src/video/video-for-preview.tsx@@ -326,7 +326,7 @@ const VideoForPreviewAssertedShowing: React.FC<tagType: 'video',getEffects: () =>ENABLE_EFFECTS ? experimentalEffectsRef.current : [],- getEffectChainState: () => effectChainStateRef.current,+ getEffectChainState: () => effectChainStateRef.current?.current!,getCurrentFrame: () => frameRef.current,});