Skip to content

🎥 Make videos programmatically with React

`remotion`: Preserve WebGL HtmlInCanvas callbacks (#8610)

Jonny Burgercc3e4bbf538f
diff --git a/packages/core/src/HtmlInCanvas.tsx b/packages/core/src/HtmlInCanvas.tsx
index ae1636b908..4ba838b803 100644
--- a/packages/core/src/HtmlInCanvas.tsx
+++ b/packages/core/src/HtmlInCanvas.tsx
@@ -426,16 +426,6 @@ const HtmlInCanvasContent = forwardRef<
throw new Error('Canvas not found');
}
- // `GPUQueue.copyElementImageToTexture` / related paths validate the
- // linked offscreen surface has a rendering context. Acquire `2d` here
- // before any capture or handler (must not call getContext on placeholder).
- const offscreen2d = offscreen.getContext('2d');
- if (!offscreen2d) {
- throw new Error(
- 'Failed to acquire 2D context for <HtmlInCanvas> offscreen canvas',
- );
- }
-
const handle = delayRender('onPaint');
if (!initializedRef.current) {
initializedRef.current = true;
diff --git a/packages/core/src/test/html-in-canvas.test.tsx b/packages/core/src/test/html-in-canvas.test.tsx
index 07f519d9ad..fc563943d7 100644
--- a/packages/core/src/test/html-in-canvas.test.tsx
+++ b/packages/core/src/test/html-in-canvas.test.tsx
@@ -93,14 +93,30 @@ Object.defineProperties(HTMLCanvasElement.prototype, {
transferControlToOffscreen: {
configurable: true,
value(this: HTMLCanvasElement) {
+ let contextMode: string | null = null;
+ const webgl2Context = {
+ drawingBufferHeight: this.height,
+ drawingBufferWidth: this.width,
+ };
+
return {
getContext: (kind: string) => {
+ if (contextMode && contextMode !== kind) {
+ return null;
+ }
+
if (kind === '2d') {
+ contextMode = kind;
const ctx = stub2dContext();
ctx.canvas = this;
return ctx;
}
+ if (kind === 'webgl2') {
+ contextMode = kind;
+ return webgl2Context;
+ }
+
return null;
},
height: this.height,
@@ -330,3 +346,37 @@ test('<HtmlInCanvas> does not apply pixel density to the live DOM transform', as
);
});
});
+test('<HtmlInCanvas> lets onInit choose a WebGL2 context', async () => {
+ let gotWebGl2Context = false;
+ let paintCalled = false;
+
+ const {container} = render(
+ <SequenceTestWrapper onRegisterSequence={() => undefined}>
+ <HtmlInCanvas
+ width={50}
+ height={50}
+ onInit={({canvas: offscreenCanvas}) => {
+ gotWebGl2Context = Boolean(offscreenCanvas.getContext('webgl2'));
+ return () => undefined;
+ }}
+ onPaint={() => {
+ paintCalled = true;
+ }}
+ >
+ <div>Test</div>
+ </HtmlInCanvas>
+ </SequenceTestWrapper>,
+ );
+
+ await waitFor(() => {
+ expect(container.querySelector('canvas')).not.toBeNull();
+ });
+
+ const canvas = container.querySelector('canvas')!;
+ canvas.dispatchEvent(new Event('paint'));
+
+ await waitFor(() => {
+ expect(gotWebGl2Context).toBe(true);
+ expect(paintCalled).toBe(true);
+ });
+});
diff --git a/packages/docs/components/demos/HtmlInCanvasDocsDemoWebGL.tsx b/packages/docs/components/demos/HtmlInCanvasDocsDemoWebGL.tsx
index 1d9d34ca9a..2cad5c5d83 100644
--- a/packages/docs/components/demos/HtmlInCanvasDocsDemoWebGL.tsx
+++ b/packages/docs/components/demos/HtmlInCanvasDocsDemoWebGL.tsx
@@ -4,6 +4,7 @@
import React, {useCallback, useRef} from 'react';
import {
AbsoluteFill,
+ getRemotionEnvironment,
HtmlInCanvas,
useCurrentFrame,
useVideoConfig,
@@ -68,6 +69,14 @@ 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,
]);
+const webGl2UnavailableMessage = () => {
+ if (getRemotionEnvironment().isRendering) {
+ return 'WebGL2 unavailable. Try rendering with the --gl=angle option. See https://remotion.dev/docs/gl-options.';
+ }
+
+ return 'WebGL2 unavailable in this browser. Check that hardware acceleration is enabled, or use the pre-rendered fallback video.';
+};
+
const HtmlInCanvasDocsWebGLInner: React.FC = () => {
const frame = useCurrentFrame();
const {width, height, fps} = useVideoConfig();
@@ -80,9 +89,7 @@ const HtmlInCanvasDocsWebGLInner: React.FC = () => {
antialias: false,
});
if (!gl) {
- throw new Error(
- 'WebGL2 unavailable. Try rendering with the --gl=angle option. See https://remotion.dev/docs/gl-options.',
- );
+ throw new Error(webGl2UnavailableMessage());
}
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
@@ -182,7 +189,7 @@ const HtmlInCanvasDocsWebGLInner: React.FC = () => {
};
export const HtmlInCanvasDocsDemoWebGL: React.FC = () => {
- const branch = useHtmlInCanvasDocsDemoBranch();
+ const branch = useHtmlInCanvasDocsDemoBranch('webgl2');
if (branch === 'pending') {
return <AbsoluteFill style={{backgroundColor: '#000'}} />;
diff --git a/packages/docs/components/demos/HtmlInCanvasDocsDemoWebGPU.tsx b/packages/docs/components/demos/HtmlInCanvasDocsDemoWebGPU.tsx
index 509767985a..167ff68238 100644
--- a/packages/docs/components/demos/HtmlInCanvasDocsDemoWebGPU.tsx
+++ b/packages/docs/components/demos/HtmlInCanvasDocsDemoWebGPU.tsx
@@ -320,7 +320,7 @@ const HtmlInCanvasDocsWebGPUInner: React.FC = () => {
};
export const HtmlInCanvasDocsDemoWebGPU: React.FC = () => {
- const branch = useHtmlInCanvasDocsDemoBranch();
+ const branch = useHtmlInCanvasDocsDemoBranch('webgpu');
if (branch === 'pending') {
return <AbsoluteFill style={{backgroundColor: '#fff'}} />;
diff --git a/packages/docs/components/demos/useHtmlInCanvasDocsDemoBranch.ts b/packages/docs/components/demos/useHtmlInCanvasDocsDemoBranch.ts
index 3effb6dca8..1ccdf74b91 100644
--- a/packages/docs/components/demos/useHtmlInCanvasDocsDemoBranch.ts
+++ b/packages/docs/components/demos/useHtmlInCanvasDocsDemoBranch.ts
@@ -2,16 +2,128 @@ import {useEffect, useState} from 'react';
import {HtmlInCanvas} from 'remotion';
export type HtmlInCanvasDocsDemoBranch = 'pending' | 'live' | 'fallback';
+export type HtmlInCanvasDocsDemoRequirement =
+ | 'html-in-canvas'
+ | 'webgl2'
+ | 'webgpu';
+
+type Gpu = {
+ requestAdapter(): Promise<unknown | null>;
+};
+
+const makeOffscreenCanvas = (): OffscreenCanvas | HTMLCanvasElement | null => {
+ if (typeof OffscreenCanvas !== 'undefined') {
+ return new OffscreenCanvas(1, 1);
+ }
+
+ if (typeof document !== 'undefined') {
+ const canvas = document.createElement('canvas');
+ canvas.width = 1;
+ canvas.height = 1;
+ return canvas;
+ }
+
+ return null;
+};
+
+const isWebGl2SupportedOnOffscreenCanvas = (): boolean => {
+ const canvas = makeOffscreenCanvas();
+ if (!canvas) {
+ return false;
+ }
+
+ try {
+ const gl = canvas.getContext('webgl2', {
+ alpha: true,
+ premultipliedAlpha: true,
+ antialias: false,
+ });
+
+ if (!gl) {
+ return false;
+ }
+
+ gl.getExtension('WEBGL_lose_context')?.loseContext();
+ return true;
+ } catch {
+ return false;
+ }
+};
+
+const isWebGpuSupportedOnOffscreenCanvas = async (): Promise<boolean> => {
+ if (typeof navigator === 'undefined') {
+ return false;
+ }
+
+ const {gpu} = navigator as unknown as {gpu?: Gpu};
+ if (!gpu) {
+ return false;
+ }
+
+ const canvas = makeOffscreenCanvas();
+ if (!canvas) {
+ return false;
+ }
+
+ try {
+ const context = (
+ canvas as unknown as {
+ getContext(id: 'webgpu'): unknown | null;
+ }
+ ).getContext('webgpu');
+
+ if (!context) {
+ return false;
+ }
+
+ return Boolean(await gpu.requestAdapter());
+ } catch {
+ return false;
+ }
+};
+
+const isRequirementSupported = (
+ requirement: HtmlInCanvasDocsDemoRequirement,
+): Promise<boolean> | boolean => {
+ if (!HtmlInCanvas.isSupported()) {
+ return false;
+ }
+
+ if (requirement === 'html-in-canvas') {
+ return true;
+ }
+
+ if (requirement === 'webgl2') {
+ return isWebGl2SupportedOnOffscreenCanvas();
+ }
+
+ return isWebGpuSupportedOnOffscreenCanvas();
+};
/**
* Avoid SSR/client hydration mismatch: support is only known after mount.
*/
-export const useHtmlInCanvasDocsDemoBranch = (): HtmlInCanvasDocsDemoBranch => {
+export const useHtmlInCanvasDocsDemoBranch = (
+ requirement: HtmlInCanvasDocsDemoRequirement = 'html-in-canvas',
+): HtmlInCanvasDocsDemoBranch => {
const [branch, setBranch] = useState<HtmlInCanvasDocsDemoBranch>('pending');
useEffect(() => {
- setBranch(HtmlInCanvas.isSupported() ? 'live' : 'fallback');
- }, []);
+ let cancelled = false;
+
+ const updateBranch = async () => {
+ const supported = await isRequirementSupported(requirement);
+ if (!cancelled) {
+ setBranch(supported ? 'live' : 'fallback');
+ }
+ };
+
+ updateBranch();
+
+ return () => {
+ cancelled = true;
+ };
+ }, [requirement]);
return branch;
};
diff --git a/packages/docs/docs/remotion/html-in-canvas.mdx b/packages/docs/docs/remotion/html-in-canvas.mdx
index 07311ece48..3aec27bf66 100644
--- a/packages/docs/docs/remotion/html-in-canvas.mdx
+++ b/packages/docs/docs/remotion/html-in-canvas.mdx
@@ -258,9 +258,6 @@ Use [`texElementImage2D`](https://github.com/WICG/html-in-canvas#2-drawelementim
<Demo type="html-in-canvas-webgl" />
-<details>
-<summary>This example is long. Expand to see it:</summary>
-
```tsx twoslash title="WebGL2: minimal full component"
/**
* Minimal WebGL2 + HtmlInCanvas sample (same code as /docs/remotion/html-in-canvas).
@@ -269,6 +266,7 @@ Use [`texElementImage2D`](https://github.com/WICG/html-in-canvas#2-drawelementim
import React, {useCallback, useRef} from 'react';
import {
AbsoluteFill,
+ getRemotionEnvironment,
HtmlInCanvas,
HtmlInCanvasOnInit,
HtmlInCanvasOnPaint,
@@ -331,6 +329,14 @@ 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,
]);
+const webGl2UnavailableMessage = () => {
+ if (getRemotionEnvironment().isRendering) {
+ return 'WebGL2 unavailable. Try rendering with the --gl=angle option. See https://remotion.dev/docs/gl-options.';
+ }
+
+ return 'WebGL2 unavailable in this browser. Check that hardware acceleration is enabled.';
+};
+
export const HtmlInCanvasDocsMinimalWebGL: React.FC = () => {
const frame = useCurrentFrame();
const {width, height, fps} = useVideoConfig();
@@ -343,9 +349,7 @@ export const HtmlInCanvasDocsMinimalWebGL: React.FC = () => {
antialias: false,
});
if (!gl) {
- throw new Error(
- 'WebGL2 unavailable. Try rendering with the --gl=angle option. See https://remotion.dev/docs/gl-options.',
- );
+ throw new Error(webGl2UnavailableMessage());
}
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
@@ -441,11 +445,8 @@ export const HtmlInCanvasDocsMinimalWebGL: React.FC = () => {
</HtmlInCanvas>
);
};
-
```
-</details>
-
### WebGPU
Use [`onInit`](#oninit) to get a WebGPU context, to request a GPU and to compile shaders.
diff --git a/packages/example/src/HtmlInCanvas/compose-webgl.tsx b/packages/example/src/HtmlInCanvas/compose-webgl.tsx
index 48dcadacd4..47a8e5b1f0 100644
--- a/packages/example/src/HtmlInCanvas/compose-webgl.tsx
+++ b/packages/example/src/HtmlInCanvas/compose-webgl.tsx
@@ -1,6 +1,7 @@
import React, {useCallback, useRef} from 'react';
import {
AbsoluteFill,
+ getRemotionEnvironment,
HtmlInCanvas,
HtmlInCanvasOnInit,
HtmlInCanvasOnPaint,
@@ -59,6 +60,14 @@ 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,
]);
+const webGl2UnavailableMessage = () => {
+ if (getRemotionEnvironment().isRendering) {
+ return 'WebGL2 unavailable. Try rendering with the --gl=angle option. See https://remotion.dev/docs/gl-options.';
+ }
+
+ return 'WebGL2 unavailable in this browser. Check that hardware acceleration is enabled.';
+};
+
export const HtmlInCanvasComposeWebGL: React.FC = () => {
const frame = useCurrentFrame();
const {width, height, durationInFrames} = useVideoConfig();
@@ -81,9 +90,7 @@ export const HtmlInCanvasComposeWebGL: React.FC = () => {
antialias: false,
});
if (!gl) {
- throw new Error(
- 'WebGL2 unavailable. Try rendering with the --gl=angle option. See https://remotion.dev/docs/gl-options.',
- );
+ throw new Error(webGl2UnavailableMessage());
}
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
diff --git a/packages/example/src/HtmlInCanvas/minimal-docs-webgl.tsx b/packages/example/src/HtmlInCanvas/minimal-docs-webgl.tsx
index 4138f9cddb..71ba2ef462 100644
--- a/packages/example/src/HtmlInCanvas/minimal-docs-webgl.tsx
+++ b/packages/example/src/HtmlInCanvas/minimal-docs-webgl.tsx
@@ -5,6 +5,7 @@
import React, {useCallback, useRef} from 'react';
import {
AbsoluteFill,
+ getRemotionEnvironment,
HtmlInCanvas,
HtmlInCanvasOnInit,
HtmlInCanvasOnPaint,
@@ -67,6 +68,14 @@ 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,
]);
+const webGl2UnavailableMessage = () => {
+ if (getRemotionEnvironment().isRendering) {
+ return 'WebGL2 unavailable. Try rendering with the --gl=angle option. See https://remotion.dev/docs/gl-options.';
+ }
+
+ return 'WebGL2 unavailable in this browser. Check that hardware acceleration is enabled.';
+};
+
export const HtmlInCanvasDocsMinimalWebGL: React.FC = () => {
const frame = useCurrentFrame();
const {width, height, fps} = useVideoConfig();
@@ -79,9 +88,7 @@ export const HtmlInCanvasDocsMinimalWebGL: React.FC = () => {
antialias: false,
});
if (!gl) {
- throw new Error(
- 'WebGL2 unavailable. Try rendering with the --gl=angle option. See https://remotion.dev/docs/gl-options.',
- );
+ throw new Error(webGl2UnavailableMessage());
}
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);