🎥 Make videos programmatically with React
cool
JonnyBurger42737ca46373
diff --git a/packages/example/src/HtmlInCanvas/apply-wave-effect.ts b/packages/example/src/HtmlInCanvas/apply-wave-effect.tsnew file mode 100644index 0000000000..ee2554f865--- /dev/null+++ b/packages/example/src/HtmlInCanvas/apply-wave-effect.ts@@ -0,0 +1,39 @@+import type {ApplyCanvasEffect} from './html-in-canvas';++// Apply a vertical wave effect: shift columns of the captured image up and+// down with a sine wave that moves over time.+export const applyWaveEffect: ApplyCanvasEffect = ({+ source,+ target,+ frame,+ width,+ height,+}) => {+ const ctx = target.getContext('2d');+ if (!ctx) {+ return;+ }++ ctx.fillStyle = 'black';+ ctx.fillRect(0, 0, width, height);++ const sliceWidth = 4;+ const amplitude = 60;+ const wavelength = 240;++ for (let x = 0; x < width; x += sliceWidth) {+ const offset =+ Math.sin((x / wavelength) * Math.PI * 2 + frame / 6) * amplitude;+ ctx.drawImage(+ source,+ x,+ 0,+ sliceWidth,+ height,+ x,+ offset,+ sliceWidth,+ height,+ );+ }+};diff --git a/packages/example/src/HtmlInCanvas/html-in-canvas.tsx b/packages/example/src/HtmlInCanvas/html-in-canvas.tsxnew file mode 100644index 0000000000..efc8ed3037--- /dev/null+++ b/packages/example/src/HtmlInCanvas/html-in-canvas.tsx@@ -0,0 +1,187 @@+import React, {useEffect, useRef} from 'react';+import {+ cancelRender,+ continueRender,+ delayRender,+ useCurrentFrame,+} from 'remotion';++// 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).+type Canvas2DWithDrawElement = CanvasRenderingContext2D & {+ drawElementImage: (+ element: Element,+ dx: number,+ dy: number,+ dwidth: number,+ dheight: number,+ ) => DOMMatrix;+};++type HTMLCanvasWithLayoutSubtree = HTMLCanvasElement & {+ layoutSubtree?: boolean;+ requestPaint: () => void;+};++const isHtmlInCanvasSupported = () => {+ if (typeof document === 'undefined') {+ return false;+ }++ const canvas = document.createElement(+ 'canvas',+ ) as HTMLCanvasWithLayoutSubtree;+ const ctx = canvas.getContext('2d') as Canvas2DWithDrawElement | null;+ return (+ typeof ctx?.drawElementImage === 'function' &&+ typeof canvas.requestPaint === 'function'+ );+};++export type ApplyCanvasEffect = (params: {+ source: HTMLCanvasElement;+ target: HTMLCanvasElement;+ frame: number;+ width: number;+ height: number;+}) => void;++export const HtmlInCanvas: React.FC<{+ readonly width: number;+ readonly height: number;+ readonly applyEffect: ApplyCanvasEffect;+ readonly children: React.ReactNode;+}> = ({width, height, applyEffect, children}) => {+ const frame = useCurrentFrame();++ const sourceCanvasRef = useRef<HTMLCanvasElement | null>(null);+ const sceneRef = useRef<HTMLDivElement | null>(null);+ const outputCanvasRef = useRef<HTMLCanvasElement | null>(null);++ // Mark the source canvas as a layoutSubtree root once on mount so its+ // child <div ref={sceneRef}> participates in layout/paint and can be+ // captured via drawElementImage().+ useEffect(() => {+ if (!isHtmlInCanvasSupported()) {+ cancelRender(+ new Error(+ 'HTML in Canvas is not supported. Open this page in Chrome Canary with chrome://flags/#canvas-draw-element enabled.',+ ),+ );+ return;+ }++ const sourceCanvas =+ sourceCanvasRef.current as HTMLCanvasWithLayoutSubtree | null;+ if (!sourceCanvas) {+ return;+ }++ sourceCanvas.layoutSubtree = true;+ }, []);++ useEffect(() => {+ const sourceCanvas =+ sourceCanvasRef.current as HTMLCanvasWithLayoutSubtree | null;+ const sceneEl = sceneRef.current;+ const outputCanvas = outputCanvasRef.current;+ if (!sourceCanvas || !sceneEl || !outputCanvas) {+ return;+ }++ const ctx = sourceCanvas.getContext('2d') as Canvas2DWithDrawElement | null;+ if (!ctx) {+ return;+ }++ const handle = delayRender(`Painting HTML in canvas (frame ${frame})`);+ let resolved = false;+ let cancelled = false;++ const capture = () => {+ if (cancelled) {+ return;+ }++ try {+ ctx.reset();+ ctx.drawElementImage(sceneEl, 0, 0, width, height);++ applyEffect({+ source: sourceCanvas,+ target: outputCanvas,+ frame,+ width,+ height,+ });++ resolved = true;+ continueRender(handle);+ } catch (err) {+ resolved = true;+ cancelRender(err as Error);+ }+ };++ const onPaint = () => {+ sourceCanvas.removeEventListener('paint', onPaint);+ capture();+ };++ sourceCanvas.addEventListener('paint', onPaint);+ sourceCanvas.requestPaint();++ return () => {+ cancelled = true;+ sourceCanvas.removeEventListener('paint', onPaint);+ if (!resolved) {+ continueRender(handle);+ }+ };+ }, [frame, width, height, applyEffect]);++ return (+ <>+ <canvas+ ref={sourceCanvasRef}+ width={width}+ height={height}+ style={{+ position: 'absolute',+ inset: 0,+ width,+ height,+ }}+ >+ <div+ ref={sceneRef}+ style={{+ width,+ height,+ }}+ >+ {children}+ </div>+ </canvas>+ <canvas+ ref={outputCanvasRef}+ width={width}+ height={height}+ style={{+ position: 'absolute',+ inset: 0,+ width,+ height,+ }}+ />+ </>+ );+};diff --git a/packages/example/src/HtmlInCanvas/index.tsx b/packages/example/src/HtmlInCanvas/index.tsxindex f3085eb39f..14aa93c076 100644--- a/packages/example/src/HtmlInCanvas/index.tsx+++ b/packages/example/src/HtmlInCanvas/index.tsx@@ -1,52 +1,7 @@-import React, {useEffect, useRef} from 'react';-import {- AbsoluteFill,- cancelRender,- continueRender,- delayRender,- useCurrentFrame,- useVideoConfig,-} from 'remotion';--// 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).-type Canvas2DWithDrawElement = CanvasRenderingContext2D & {- drawElementImage: (- element: Element,- dx: number,- dy: number,- dwidth: number,- dheight: number,- ) => DOMMatrix;-};--type HTMLCanvasWithLayoutSubtree = HTMLCanvasElement & {- layoutSubtree?: boolean;- requestPaint: () => void;-};--const isHtmlInCanvasSupported = () => {- if (typeof document === 'undefined') {- return false;- }-- const canvas = document.createElement(- 'canvas',- ) as HTMLCanvasWithLayoutSubtree;- const ctx = canvas.getContext('2d') as Canvas2DWithDrawElement | null;- return (- typeof ctx?.drawElementImage === 'function' &&- typeof canvas.requestPaint === 'function'- );-};+import React from 'react';+import {AbsoluteFill, useCurrentFrame, useVideoConfig} from 'remotion';+import {applyWaveEffect} from './apply-wave-effect';+import {HtmlInCanvas} from './html-in-canvas';const Scene: React.FC = () => {const frame = useCurrentFrame();@@ -56,11 +11,8 @@ const Scene: React.FC = () => {const hue = Math.round(progress * 360);return (- <div+ <AbsoluteFillstyle={{- width: '100%',- height: '100%',- display: 'flex',flexDirection: 'column',alignItems: 'center',justifyContent: 'center',@@ -72,224 +24,25 @@ const Scene: React.FC = () => {fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif',textAlign: 'center',+ fontSize: 56,+ fontWeight: 600,+ padding: '20px 40px',+ borderRadius: 24,}}>- <div style={{fontSize: 120, fontWeight: 800, letterSpacing: -4}}>- HTML in Canvas- </div>- <div- style={{- fontSize: 56,- fontWeight: 600,- padding: '20px 40px',- borderRadius: 24,- background: 'rgba(0, 0, 0, 0.35)',- }}- >- Frame {frame} captured via{' '}- <code- style={{- fontFamily: 'ui-monospace, SFMono-Regular, monospace',- background: 'rgba(255, 255, 255, 0.2)',- padding: '4px 12px',- borderRadius: 8,- }}- >- drawElementImage()- </code>- </div>- <div style={{display: 'flex', gap: 24}}>- {[0, 1, 2, 3, 4].map((i) => {- const delay = i * 4;- const t = Math.max(0, Math.min(1, (frame - delay) / 30));- const scale = 0.6 + 0.4 * Math.sin(progress * Math.PI * 2 + i);- return (- <div- key={i}- style={{- width: 90,- height: 90,- borderRadius: '50%',- background: 'white',- opacity: t,- transform: `scale(${scale})`,- }}- />- );- })}- </div>- </div>+ {frame}+ </AbsoluteFill>);};-// Apply a vertical wave effect: shift columns of the captured image up and-// down with a sine wave that moves over time.-const applyWaveEffect = ({- source,- target,- frame,- width,- height,-}: {- source: HTMLCanvasElement;- target: HTMLCanvasElement;- frame: number;- width: number;- height: number;-}) => {- const ctx = target.getContext('2d');- if (!ctx) {- return;- }-- ctx.fillStyle = 'black';- ctx.fillRect(0, 0, width, height);-- const sliceWidth = 4;- const amplitude = 60;- const wavelength = 240;-- for (let x = 0; x < width; x += sliceWidth) {- const offset =- Math.sin((x / wavelength) * Math.PI * 2 + frame / 6) * amplitude;- ctx.drawImage(- source,- x,- 0,- sliceWidth,- height,- x,- offset,- sliceWidth,- height,- );- }-};-export const HtmlInCanvasDemo: React.FC = () => {- const frame = useCurrentFrame();const {width, height} = useVideoConfig();- const sourceCanvasRef = useRef<HTMLCanvasElement | null>(null);- const sceneRef = useRef<HTMLDivElement | null>(null);- const outputCanvasRef = useRef<HTMLCanvasElement | null>(null);-- // Mark the source canvas as a layoutSubtree root once on mount so its- // child <div ref={sceneRef}> participates in layout/paint and can be- // captured via drawElementImage().- useEffect(() => {- if (!isHtmlInCanvasSupported()) {- cancelRender(- new Error(- 'HTML in Canvas is not supported. Open this page in Chrome Canary with chrome://flags/#canvas-draw-element enabled.',- ),- );- return;- }-- const sourceCanvas =- sourceCanvasRef.current as HTMLCanvasWithLayoutSubtree | null;- if (!sourceCanvas) {- return;- }-- sourceCanvas.layoutSubtree = true;- }, []);-- useEffect(() => {- const sourceCanvas =- sourceCanvasRef.current as HTMLCanvasWithLayoutSubtree | null;- const sceneEl = sceneRef.current;- const outputCanvas = outputCanvasRef.current;- if (!sourceCanvas || !sceneEl || !outputCanvas) {- return;- }-- const ctx = sourceCanvas.getContext('2d') as Canvas2DWithDrawElement | null;- if (!ctx) {- return;- }-- const handle = delayRender(`Painting HTML in canvas (frame ${frame})`);- let resolved = false;- let cancelled = false;-- const capture = () => {- if (cancelled) {- return;- }-- try {- ctx.reset();- ctx.drawElementImage(sceneEl, 0, 0, width, height);-- applyWaveEffect({- source: sourceCanvas,- target: outputCanvas,- frame,- width,- height,- });-- resolved = true;- continueRender(handle);- } catch (err) {- resolved = true;- cancelRender(err as Error);- }- };-- const onPaint = () => {- sourceCanvas.removeEventListener('paint', onPaint);- capture();- };-- sourceCanvas.addEventListener('paint', onPaint);- sourceCanvas.requestPaint();-- return () => {- cancelled = true;- sourceCanvas.removeEventListener('paint', onPaint);- if (!resolved) {- continueRender(handle);- }- };- }, [frame, width, height]);-return (<AbsoluteFill style={{backgroundColor: 'black'}}>- <canvas- ref={sourceCanvasRef}- width={width}- height={height}- style={{- position: 'absolute',- inset: 0,- width,- height,- }}- >- <div- ref={sceneRef}- style={{- width,- height,- }}- >- <Scene />- </div>- </canvas>- <canvas- ref={outputCanvasRef}- width={width}- height={height}- style={{- position: 'absolute',- inset: 0,- width,- height,- }}- />+ <HtmlInCanvas width={width} height={height} applyEffect={applyWaveEffect}>+ <Scene />+ </HtmlInCanvas></AbsoluteFill>);};