Skip to content

πŸŽ₯ Make videos programmatically with React

cool

JonnyBurger6f6cc5781bcb
diff --git a/packages/core/src/HtmlInCanvas.tsx b/packages/core/src/HtmlInCanvas.tsx
index bdc7b536a1..6ef61f31a2 100644
--- a/packages/core/src/HtmlInCanvas.tsx
+++ b/packages/core/src/HtmlInCanvas.tsx
@@ -352,6 +352,21 @@ const HtmlInCanvasInner: React.FC<
offscreenCanvas.height = height;
try {
+ const layoutCanvas = canvas2dRef.current;
+ if (!layoutCanvas) {
+ throw new Error('Canvas not found');
+ }
+
+ // `GPUQueue.copyElementImageToTexture` / related paths validate the
+ // layout canvas has a rendering context. `runEffectChain` only runs
+ // after `onPaint`, so acquire `2d` here before any capture or handler.
+ const layout2d = layoutCanvas.getContext('2d');
+ if (!layout2d) {
+ throw new Error(
+ 'Failed to acquire 2D context for <HtmlInCanvas> layout canvas',
+ );
+ }
+
const handle = delayRender('onPaint');
if (!initializedRef.current) {
initializedRef.current = true;
@@ -361,7 +376,7 @@ const HtmlInCanvasInner: React.FC<
// can invalidate the capture's paint context, leaving subsequent
// uploads (e.g. `copyElementImageToTexture`) failing with
// "No context found for ElementImage" on the very first paint.
- const initImage = canvas2dRef.current?.captureElementImage(element);
+ const initImage = layoutCanvas.captureElementImage(element);
const currentOnInit = onInitRef.current;
if (currentOnInit) {
const cleanup = await currentOnInit({
@@ -385,7 +400,7 @@ const HtmlInCanvasInner: React.FC<
const handler = onPaintRef.current ?? defaultOnPaint;
- const elImage = canvas2dRef.current?.captureElementImage(element);
+ const elImage = layoutCanvas.captureElementImage(element);
await handler({canvas: offscreenCanvas, element, elementImage: elImage!});
await runEffectChain({
diff --git a/packages/docs/components/demos/HtmlInCanvasDocsDemo2DBlur.tsx b/packages/docs/components/demos/HtmlInCanvasDocsDemo2DBlur.tsx
new file mode 100644
index 0000000000..07341e7dd9
--- /dev/null
+++ b/packages/docs/components/demos/HtmlInCanvasDocsDemo2DBlur.tsx
@@ -0,0 +1,70 @@
+import React, {useCallback} from 'react';
+import {
+ AbsoluteFill,
+ HtmlInCanvas,
+ type HtmlInCanvasOnPaint,
+ useCurrentFrame,
+ useVideoConfig,
+} from 'remotion';
+import {HtmlInCanvasDocsVideoFallback} from './HtmlInCanvasDocsVideoFallback';
+import {useHtmlInCanvasDocsDemoBranch} from './useHtmlInCanvasDocsDemoBranch';
+
+const BLUR_MIN_PX = 4;
+const BLUR_MAX_PX = 22;
+const BLUR_CYCLES_PER_SECOND = 0.35;
+
+const HtmlInCanvasDocsDemo2DBlurInner: React.FC = () => {
+ const frame = useCurrentFrame();
+ const {width, height, fps} = useVideoConfig();
+
+ const onPaint: HtmlInCanvasOnPaint = useCallback(
+ ({canvas, element, elementImage}) => {
+ const ctx = canvas.getContext('2d');
+ if (!ctx) {
+ throw new Error('Failed to acquire 2D context');
+ }
+
+ const t = (frame / fps) * Math.PI * 2 * BLUR_CYCLES_PER_SECOND;
+ const blurPx =
+ BLUR_MIN_PX +
+ (BLUR_MAX_PX - BLUR_MIN_PX) * (0.5 + 0.5 * Math.sin(t));
+
+ ctx.reset();
+ ctx.filter = `blur(${blurPx}px)`;
+ const transform = ctx.drawElementImage(elementImage, 0, 0);
+ element.style.transform = transform.toString();
+ },
+ [frame, fps],
+ );
+
+ return (
+ <HtmlInCanvas width={width} height={height} onPaint={onPaint}>
+ <AbsoluteFill
+ style={{
+ justifyContent: 'center',
+ alignItems: 'center',
+ backgroundColor: '#1a1a2e',
+ color: 'white',
+ fontSize: 120,
+ fontFamily: 'sans-serif',
+ }}
+ >
+ <h1 style={{margin: 0, fontSize: 120}}>Hello</h1>
+ </AbsoluteFill>
+ </HtmlInCanvas>
+ );
+};
+
+export const HtmlInCanvasDocsDemo2DBlur: React.FC = () => {
+ const branch = useHtmlInCanvasDocsDemoBranch();
+
+ if (branch === 'pending') {
+ return <AbsoluteFill style={{backgroundColor: '#1a1a2e'}} />;
+ }
+
+ if (branch === 'fallback') {
+ return <HtmlInCanvasDocsVideoFallback relativeSrc="img/html-in-canvas-2d-blur.mp4" />;
+ }
+
+ return <HtmlInCanvasDocsDemo2DBlurInner />;
+};
diff --git a/packages/docs/components/demos/HtmlInCanvasDocsDemoWebGL.tsx b/packages/docs/components/demos/HtmlInCanvasDocsDemoWebGL.tsx
new file mode 100644
index 0000000000..9385e6fab3
--- /dev/null
+++ b/packages/docs/components/demos/HtmlInCanvasDocsDemoWebGL.tsx
@@ -0,0 +1,196 @@
+/**
+ * Minimal WebGL2 + HtmlInCanvas (same as packages/example minimal-docs-webgl).
+ */
+import React, {useCallback, useRef} from 'react';
+import {
+ AbsoluteFill,
+ HtmlInCanvas,
+ useCurrentFrame,
+ useVideoConfig,
+ type HtmlInCanvasOnInit,
+ type HtmlInCanvasOnPaint,
+} from 'remotion';
+import {HtmlInCanvasDocsVideoFallback} from './HtmlInCanvasDocsVideoFallback';
+import {useHtmlInCanvasDocsDemoBranch} from './useHtmlInCanvasDocsDemoBranch';
+
+type GlState = {
+ gl: WebGL2RenderingContext;
+ program: WebGLProgram;
+ uTex: WebGLUniformLocation | null;
+ uTime: WebGLUniformLocation | null;
+ texture: WebGLTexture;
+ vao: WebGLVertexArrayObject;
+};
+
+const VS = `#version 300 es
+in vec2 a_pos;
+in vec2 a_uv;
+out vec2 v_uv;
+void main() {
+ gl_Position = vec4(a_pos, 0.0, 1.0);
+ v_uv = a_uv;
+}`;
+
+const FS = `#version 300 es
+precision highp float;
+uniform sampler2D u_tex;
+uniform float u_time;
+in vec2 v_uv;
+out vec4 o;
+void main() {
+ vec2 uv = v_uv;
+ uv.x += 0.045 * sin(v_uv.y * 32.0 + u_time * 5.0);
+ uv.y += 0.038 * sin(v_uv.x * 26.0 + u_time * 4.0);
+ o = texture(u_tex, uv);
+}`;
+
+function linkProgram(
+ gl: WebGL2RenderingContext,
+ vsSrc: string,
+ fsSrc: string,
+): WebGLProgram {
+ const vert = gl.createShader(gl.VERTEX_SHADER)!;
+ gl.shaderSource(vert, vsSrc);
+ gl.compileShader(vert);
+ const frag = gl.createShader(gl.FRAGMENT_SHADER)!;
+ gl.shaderSource(frag, fsSrc);
+ 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,
+]);
+
+const HtmlInCanvasDocsWebGLInner: React.FC = () => {
+ const frame = useCurrentFrame();
+ const {width, height, fps} = useVideoConfig();
+ const gpuRef = useRef<GlState | null>(null);
+
+ const onInit: HtmlInCanvasOnInit = useCallback(({canvas}) => {
+ const gl = canvas.getContext('webgl2', {
+ alpha: true,
+ premultipliedAlpha: true,
+ antialias: false,
+ });
+ if (!gl) {
+ throw new Error('WebGL2 unavailable');
+ }
+
+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
+
+ const program = linkProgram(gl, VS, FS);
+ const uTex = gl.getUniformLocation(program, 'u_tex');
+ const uTime = gl.getUniformLocation(program, 'u_time');
+
+ 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);
+
+ gpuRef.current = {gl, program, uTex, uTime, texture, vao};
+
+ return () => {
+ gl.deleteProgram(program);
+ gl.deleteTexture(texture);
+ gl.deleteVertexArray(vao);
+ gl.deleteBuffer(buffer);
+ gpuRef.current = null;
+ };
+ }, []);
+
+ const onPaint: HtmlInCanvasOnPaint = useCallback(
+ ({elementImage}) => {
+ const gpu = gpuRef.current;
+ if (!gpu) {
+ 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.texElementImage2D(
+ gl.TEXTURE_2D,
+ 0,
+ gl.RGBA,
+ gl.RGBA,
+ gl.UNSIGNED_BYTE,
+ elementImage,
+ );
+
+ if (gpu.uTex) {
+ gl.uniform1i(gpu.uTex, 0);
+ }
+
+ if (gpu.uTime) {
+ gl.uniform1f(gpu.uTime, frame / fps);
+ }
+
+ gl.bindVertexArray(gpu.vao);
+ gl.drawArrays(gl.TRIANGLES, 0, 6);
+ },
+ [frame, fps],
+ );
+
+ return (
+ <HtmlInCanvas
+ width={width}
+ height={height}
+ onInit={onInit}
+ onPaint={onPaint}
+ >
+ <AbsoluteFill
+ style={{
+ justifyContent: 'center',
+ alignItems: 'center',
+ color: 'white',
+ backgroundColor: 'black',
+ fontSize: 120,
+ }}
+ >
+ {/* Explicit font size: Infima/Docusaurus global `h1` rules otherwise override the parent font size inside the docs Player. */}
+ <h1 style={{margin: 0, fontSize: 120}}>Hello</h1>
+ </AbsoluteFill>
+ </HtmlInCanvas>
+ );
+};
+
+export const HtmlInCanvasDocsDemoWebGL: React.FC = () => {
+ const branch = useHtmlInCanvasDocsDemoBranch();
+
+ if (branch === 'pending') {
+ return <AbsoluteFill style={{backgroundColor: '#000'}} />;
+ }
+
+ if (branch === 'fallback') {
+ return (
+ <HtmlInCanvasDocsVideoFallback relativeSrc="img/html-in-canvas-webgl.mp4" />
+ );
+ }
+
+ return <HtmlInCanvasDocsWebGLInner />;
+};
diff --git a/packages/docs/components/demos/HtmlInCanvasDocsDemoWebGPU.tsx b/packages/docs/components/demos/HtmlInCanvasDocsDemoWebGPU.tsx
new file mode 100644
index 0000000000..9f7aaa0ae7
--- /dev/null
+++ b/packages/docs/components/demos/HtmlInCanvasDocsDemoWebGPU.tsx
@@ -0,0 +1,336 @@
+import React, {useCallback, useRef} from 'react';
+import {
+ AbsoluteFill,
+ HtmlInCanvas,
+ type HtmlInCanvasOnInit,
+ type HtmlInCanvasOnPaint,
+ useCurrentFrame,
+ useVideoConfig,
+} from 'remotion';
+import {HtmlInCanvasDocsVideoFallback} from './HtmlInCanvasDocsVideoFallback';
+import {useHtmlInCanvasDocsDemoBranch} from './useHtmlInCanvasDocsDemoBranch';
+
+// Minimal WebGPU types β€” `@webgpu/types` is intentionally not a dependency,
+// matching the convention in `packages/core/src/canvas-effects/gpu-device.ts`.
+type Gpu = {
+ requestAdapter(): Promise<GpuAdapter | null>;
+ getPreferredCanvasFormat(): string;
+};
+type GpuAdapter = {requestDevice(): Promise<GpuDevice>};
+type GpuTextureView = unknown;
+type GpuTexture = {createView(): GpuTextureView; destroy(): void};
+type GpuBuffer = {destroy(): void};
+type GpuBindGroup = unknown;
+type GpuPipeline = unknown;
+type GpuSampler = unknown;
+type GpuShaderModule = unknown;
+type GpuDevice = {
+ createShaderModule(d: {code: string}): GpuShaderModule;
+ createRenderPipeline(d: unknown): GpuPipeline;
+ createTexture(d: unknown): GpuTexture;
+ createSampler(d?: unknown): GpuSampler;
+ createBindGroup(d: unknown): GpuBindGroup;
+ createBuffer(d: unknown): GpuBuffer;
+ createCommandEncoder(): {
+ beginRenderPass(d: unknown): {
+ setPipeline(p: GpuPipeline): void;
+ setBindGroup(i: number, b: GpuBindGroup): void;
+ draw(n: number): void;
+ end(): void;
+ };
+ finish(): unknown;
+ };
+ queue: {
+ submit(c: unknown[]): void;
+ writeBuffer(b: GpuBuffer, offset: number, data: BufferSource): void;
+ copyElementImageToTexture(
+ source: Element | ElementImage,
+ width: number,
+ height: number,
+ destination: {texture: GpuTexture},
+ ): void;
+ };
+};
+type GpuCanvasContext = {
+ configure(d: {
+ device: GpuDevice;
+ format: string;
+ alphaMode: 'premultiplied' | 'opaque';
+ }): void;
+ getCurrentTexture(): GpuTexture;
+};
+
+const WGSL = /* wgsl */ `
+struct VsOut {
+ @builtin(position) pos: vec4f,
+ @location(0) uv: vec2f,
+};
+
+@vertex
+fn vs(@builtin(vertex_index) i: u32) -> VsOut {
+ // Fullscreen triangle (slightly oversized β€” clipped to viewport).
+ var p = array(vec2f(-1.0, -3.0), vec2f(-1.0, 1.0), vec2f(3.0, 1.0));
+ var uv = array(vec2f(0.0, 2.0), vec2f(0.0, 0.0), vec2f(2.0, 0.0));
+ var o: VsOut;
+ o.pos = vec4f(p[i], 0.0, 1.0);
+ o.uv = uv[i];
+ return o;
+}
+
+struct U {
+ time: f32,
+ _pad: f32,
+ resolution: vec2f,
+};
+
+@group(0) @binding(0) var samp: sampler;
+@group(0) @binding(1) var tex: texture_2d<f32>;
+@group(0) @binding(2) var<uniform> u: U;
+
+@fragment
+fn fs(in: VsOut) -> @location(0) vec4f {
+ // Animate pixel cell size with a slow breathing motion.
+ let cell = 6.0 + sin(u.time * 0.8) * 4.0;
+ let snapped = floor(in.uv * u.resolution / cell) * cell / u.resolution;
+
+ // Slight chromatic offset between channels β€” sampled from snapped centers.
+ let off = vec2f(2.0, 0.0) / u.resolution;
+ let r = textureSample(tex, samp, snapped + off).r;
+ let g = textureSample(tex, samp, snapped).g;
+ let b = textureSample(tex, samp, snapped - off).b;
+ let a = textureSample(tex, samp, snapped).a;
+
+ // Posterize to 5 levels per channel for a flatter, screenprint look.
+ let levels = 5.0;
+ let q = floor(vec3f(r, g, b) * levels) / (levels - 1.0);
+
+ return vec4f(q, a);
+}
+`;
+
+type GpuState = {
+ device: GpuDevice;
+ context: GpuCanvasContext;
+ pipeline: GpuPipeline;
+ sampler: GpuSampler;
+ texture: GpuTexture;
+ uniformBuffer: GpuBuffer;
+ bindGroup: GpuBindGroup;
+ width: number;
+ height: number;
+};
+
+const HtmlInCanvasDocsWebGPUInner: React.FC = () => {
+ const frame = useCurrentFrame();
+ const {width, height, fps} = useVideoConfig();
+ const gpuRef = useRef<GpuState | null>(null);
+
+ const time = frame / fps;
+
+ const onInit: HtmlInCanvasOnInit = useCallback(async ({canvas}) => {
+ if (typeof navigator === 'undefined' || !('gpu' in navigator)) {
+ throw new Error('WebGPU is not available in this environment');
+ }
+
+ const {gpu} = navigator as unknown as {gpu: Gpu};
+ const adapter = await gpu.requestAdapter();
+ if (!adapter) {
+ throw new Error('No WebGPU adapter available');
+ }
+
+ const device = await adapter.requestDevice();
+ const context = (
+ canvas as unknown as {
+ getContext(id: 'webgpu'): GpuCanvasContext | null;
+ }
+ ).getContext('webgpu');
+ if (!context) {
+ throw new Error('WebGPU context unavailable on OffscreenCanvas');
+ }
+
+ const presentationFormat = gpu.getPreferredCanvasFormat();
+
+ context.configure({
+ device,
+ format: presentationFormat,
+ alphaMode: 'premultiplied',
+ });
+
+ const module = device.createShaderModule({code: WGSL});
+
+ const pipeline = device.createRenderPipeline({
+ layout: 'auto',
+ vertex: {module, entryPoint: 'vs'},
+ fragment: {
+ module,
+ entryPoint: 'fs',
+ targets: [{format: presentationFormat}],
+ },
+ primitive: {topology: 'triangle-list'},
+ });
+
+ const TextureUsage = (
+ globalThis as unknown as {
+ GPUTextureUsage: {
+ COPY_DST: number;
+ TEXTURE_BINDING: number;
+ RENDER_ATTACHMENT: number;
+ };
+ }
+ ).GPUTextureUsage;
+ const BufferUsage = (
+ globalThis as unknown as {
+ GPUBufferUsage: {UNIFORM: number; COPY_DST: number};
+ }
+ ).GPUBufferUsage;
+
+ const texture = device.createTexture({
+ size: {width: canvas.width, height: canvas.height},
+ format: 'rgba8unorm',
+ usage:
+ TextureUsage.COPY_DST |
+ TextureUsage.TEXTURE_BINDING |
+ TextureUsage.RENDER_ATTACHMENT,
+ });
+
+ const sampler = device.createSampler({
+ magFilter: 'linear',
+ minFilter: 'linear',
+ addressModeU: 'clamp-to-edge',
+ addressModeV: 'clamp-to-edge',
+ });
+
+ const uniformBuffer = device.createBuffer({
+ size: 16,
+ usage: BufferUsage.UNIFORM | BufferUsage.COPY_DST,
+ });
+
+ const bindGroup = device.createBindGroup({
+ layout: (
+ pipeline as unknown as {
+ getBindGroupLayout(i: number): unknown;
+ }
+ ).getBindGroupLayout(0),
+ entries: [
+ {binding: 0, resource: sampler},
+ {binding: 1, resource: texture.createView()},
+ {binding: 2, resource: {buffer: uniformBuffer}},
+ ],
+ });
+
+ gpuRef.current = {
+ device,
+ context,
+ pipeline,
+ sampler,
+ texture,
+ uniformBuffer,
+ bindGroup,
+ width: canvas.width,
+ height: canvas.height,
+ };
+
+ return () => {
+ texture.destroy();
+ uniformBuffer.destroy();
+ gpuRef.current = null;
+ };
+ }, []);
+
+ const onPaint: HtmlInCanvasOnPaint = useCallback(
+ ({elementImage}) => {
+ const gpu = gpuRef.current;
+ if (!gpu) {
+ return;
+ }
+
+ const {device, context, pipeline, texture, bindGroup, uniformBuffer} =
+ gpu;
+
+ device.queue.copyElementImageToTexture(
+ elementImage,
+ gpu.width,
+ gpu.height,
+ {texture},
+ );
+
+ const uniforms = new Float32Array([time, 0, gpu.width, gpu.height]);
+ device.queue.writeBuffer(uniformBuffer, 0, uniforms);
+
+ const encoder = device.createCommandEncoder();
+ const view = context.getCurrentTexture().createView();
+ const pass = encoder.beginRenderPass({
+ colorAttachments: [
+ {
+ view,
+ clearValue: {r: 0, g: 0, b: 0, a: 0},
+ loadOp: 'clear',
+ storeOp: 'store',
+ },
+ ],
+ });
+ pass.setPipeline(pipeline);
+ pass.setBindGroup(0, bindGroup);
+ pass.draw(3);
+ pass.end();
+ device.queue.submit([encoder.finish()]);
+ },
+ [time],
+ );
+
+ return (
+ <AbsoluteFill
+ style={{
+ justifyContent: 'center',
+ alignItems: 'center',
+ }}
+ >
+ <HtmlInCanvas
+ width={width}
+ height={height}
+ onInit={onInit}
+ onPaint={onPaint}
+ >
+ <AbsoluteFill
+ style={{
+ backgroundColor: 'white',
+ color: 'black',
+ justifyContent: 'center',
+ alignItems: 'center',
+ fontSize: 120,
+ fontFamily: 'sans-serif',
+ fontWeight: 'bold',
+ }}
+ >
+ {/* Explicit font size: Infima/Docusaurus global `h1` rules otherwise override the parent font size inside the docs Player. */}
+ <h1
+ style={{
+ margin: 0,
+ fontSize: 120,
+ fontFamily: 'sans-serif',
+ fontWeight: 'bold',
+ }}
+ >
+ Hello, World!
+ </h1>
+ </AbsoluteFill>
+ </HtmlInCanvas>
+ </AbsoluteFill>
+ );
+};
+
+export const HtmlInCanvasDocsDemoWebGPU: React.FC = () => {
+ const branch = useHtmlInCanvasDocsDemoBranch();
+
+ if (branch === 'pending') {
+ return <AbsoluteFill style={{backgroundColor: '#fff'}} />;
+ }
+
+ if (branch === 'fallback') {
+ return (
+ <HtmlInCanvasDocsVideoFallback relativeSrc="img/html-in-canvas-webgpu.mp4" />
+ );
+ }
+
+ return <HtmlInCanvasDocsWebGPUInner />;
+};
diff --git a/packages/docs/components/demos/HtmlInCanvasDocsVideoFallback.tsx b/packages/docs/components/demos/HtmlInCanvasDocsVideoFallback.tsx
new file mode 100644
index 0000000000..8c591b0928
--- /dev/null
+++ b/packages/docs/components/demos/HtmlInCanvasDocsVideoFallback.tsx
@@ -0,0 +1,52 @@
+import {Video} from '@remotion/media';
+import React from 'react';
+import {AbsoluteFill, staticFile, useVideoConfig} from 'remotion';
+
+/**
+ * Pre-rendered fallback when `HtmlInCanvas.isHtmlInCanvasSupported()` is false.
+ * `relativeSrc` is relative to the docs site static root (e.g. `img/foo.mp4`).
+ *
+ * Typography is sized vs. composition width so it stays legible when the Player
+ * scales a 1920Γ—1080 frame down (~500px wide in docs).
+ */
+export const HtmlInCanvasDocsVideoFallback: React.FC<{
+ readonly relativeSrc: string;
+}> = ({relativeSrc}) => {
+ const {width} = useVideoConfig();
+ const fontSize = Math.round(width * 0.052);
+ const padY = Math.round(width * 0.022);
+ const padX = Math.round(width * 0.028);
+
+ return (
+ <AbsoluteFill>
+ <Video
+ loop
+ muted
+ src={staticFile(relativeSrc)}
+ style={{
+ width: '100%',
+ height: '100%',
+ objectFit: 'contain',
+ }}
+ />
+ <div
+ style={{
+ position: 'absolute',
+ bottom: 0,
+ left: 0,
+ right: 0,
+ padding: `${padY}px ${padX}px`,
+ background: 'rgba(0, 0, 0, 0.78)',
+ color: '#fff',
+ fontSize,
+ lineHeight: 1.35,
+ fontWeight: 600,
+ textAlign: 'center',
+ fontFamily: 'var(--ifm-font-family-base)',
+ }}
+ >
+ HTML-in-canvas is not supported in this browser β€” playing video.
+ </div>
+ </AbsoluteFill>
+ );
+};
diff --git a/packages/docs/components/demos/index.tsx b/packages/docs/components/demos/index.tsx
index 512f1d2a28..7b9d8fc448 100644
--- a/packages/docs/components/demos/index.tsx
+++ b/packages/docs/components/demos/index.tsx
@@ -5,6 +5,9 @@ import {AbsoluteFill} from 'remotion';
import {Control} from './control';
import type {DemoType} from './types';
import {
+ htmlInCanvasDemo2DBlur,
+ htmlInCanvasDemoWebGL,
+ htmlInCanvasDemoWebGPU,
animationMathDemo,
arrowDemo,
circleDemo,
@@ -53,6 +56,9 @@ const container: React.CSSProperties = {
};
const demos: DemoType[] = [
+ htmlInCanvasDemo2DBlur,
+ htmlInCanvasDemoWebGL,
+ htmlInCanvasDemoWebGPU,
noiseDemo,
arrowDemo,
triangleDemo,
@@ -175,6 +181,7 @@ export const Demo: React.FC<{
inputProps={{...state, darkMode: colorMode === 'dark'}}
autoPlay={demo.autoPlay}
controls={demo.controls}
+ initiallyMuted
loop
/>
<div className={styles.containerrow}>
diff --git a/packages/docs/components/demos/types.ts b/packages/docs/components/demos/types.ts
index 55795e9736..4f27719493 100644
--- a/packages/docs/components/demos/types.ts
+++ b/packages/docs/components/demos/types.ts
@@ -15,6 +15,9 @@ import {ArrowDemo} from './Arrow';
import {CircleDemo} from './Circle';
import {EllipseDemo} from './Ellipse';
import {HeartDemo} from './Heart';
+import {HtmlInCanvasDocsDemo2DBlur} from './HtmlInCanvasDocsDemo2DBlur';
+import {HtmlInCanvasDocsDemoWebGL} from './HtmlInCanvasDocsDemoWebGL';
+import {HtmlInCanvasDocsDemoWebGPU} from './HtmlInCanvasDocsDemoWebGPU';
import {LightLeakDemoComp} from './LightLeakDemo';
import {NoiseComp} from './NoiseDemo';
import {PieDemo} from './Pie';
@@ -1197,3 +1200,39 @@ export const transitionSeriesEnterExitDemo: DemoType = {
},
],
};
+
+export const htmlInCanvasDemo2DBlur: DemoType = {
+ comp: HtmlInCanvasDocsDemo2DBlur,
+ compHeight: 1080,
+ compWidth: 1920,
+ durationInFrames: 120,
+ fps: 30,
+ id: 'html-in-canvas-2d-blur',
+ autoPlay: true,
+ controls: true,
+ options: [],
+};
+
+export const htmlInCanvasDemoWebGL: DemoType = {
+ comp: HtmlInCanvasDocsDemoWebGL,
+ compHeight: 1080,
+ compWidth: 1920,
+ durationInFrames: 120,
+ fps: 30,
+ id: 'html-in-canvas-webgl',
+ autoPlay: true,
+ controls: true,
+ options: [],
+};
+
+export const htmlInCanvasDemoWebGPU: DemoType = {
+ comp: HtmlInCanvasDocsDemoWebGPU,
+ compHeight: 1080,
+ compWidth: 1920,
+ durationInFrames: 120,
+ fps: 30,
+ id: 'html-in-canvas-webgpu',
+ autoPlay: true,
+ controls: true,
+ options: [],
+};
diff --git a/packages/docs/components/demos/useHtmlInCanvasDocsDemoBranch.ts b/packages/docs/components/demos/useHtmlInCanvasDocsDemoBranch.ts
new file mode 100644
index 0000000000..5b524b08b1
--- /dev/null
+++ b/packages/docs/components/demos/useHtmlInCanvasDocsDemoBranch.ts
@@ -0,0 +1,19 @@
+import {useEffect, useState} from 'react';
+import {HtmlInCanvas} from 'remotion';
+
+export type HtmlInCanvasDocsDemoBranch = 'pending' | 'live' | 'fallback';
+
+/**
+ * Avoid SSR/client hydration mismatch: support is only known after mount.
+ */
+export const useHtmlInCanvasDocsDemoBranch = (): HtmlInCanvasDocsDemoBranch => {
+ const [branch, setBranch] = useState<HtmlInCanvasDocsDemoBranch>('pending');
+
+ useEffect(() => {
+ setBranch(
+ HtmlInCanvas.isHtmlInCanvasSupported() ? 'live' : 'fallback',
+ );
+ }, []);
+
+ return branch;
+};
diff --git a/packages/docs/docs/remotion/html-in-canvas.mdx b/packages/docs/docs/remotion/html-in-canvas.mdx
index 9ff78c3957..2b4eb432a2 100644
--- a/packages/docs/docs/remotion/html-in-canvas.mdx
+++ b/packages/docs/docs/remotion/html-in-canvas.mdx
@@ -10,10 +10,6 @@ This component renders its children into a `<canvas>` using the browser’s [HTM
HTML-in-canvas is only available in Chrome 149 and later and if the `chrome://flags/#canvas-draw-element` flag is enabled.
-## Example
-
-`<HtmlInCanvas>` with default 2D painting (omit [`onPaint`](#onpaint)):
-
```tsx twoslash title="MyComp.tsx"
import {HtmlInCanvas} from 'remotion';
@@ -117,39 +113,94 @@ Inherited from [`<Sequence>`](/docs/sequence#from).
### 2D
-Call [`drawElementImage`](https://github.com/WICG/html-in-canvas) on the 2D context to draw `elementImage` into the bitmap.
+Call [`drawElementImage()`](https://github.com/WICG/html-in-canvas) on the 2D context to draw `elementImage` into the bitmap.
HTML-in-canvas recommends that you use the return value and assign it to `element.style.transform`, so that the original DOM element matches the transform, so that selection still works.
-```tsx twoslash title="2D: filters + drawElementImage"
-import {HtmlInCanvasOnPaint} from 'remotion';
+For 2D, you usually do not need `onInit`.
-const onPaint: HtmlInCanvasOnPaint = ({canvas, element, elementImage}) => {
- const ctx = canvas.getContext('2d');
- if (!ctx) {
- throw new Error('Failed to acquire 2D context');
- }
+<Demo type="html-in-canvas-2d-blur" />
- ctx.reset();
- ctx.filter = 'blur(10px)';
- const transform = ctx.drawElementImage(elementImage, 0, 0);
- element.style.transform = transform.toString();
+```tsx twoslash title="2D: animated blur + drawElementImage"
+import React, {useCallback} from 'react';
+import {
+ AbsoluteFill,
+ HtmlInCanvas,
+ type HtmlInCanvasOnPaint,
+ useCurrentFrame,
+ useVideoConfig,
+} from 'remotion';
+
+const BLUR_MIN_PX = 4;
+const BLUR_MAX_PX = 22;
+const BLUR_CYCLES_PER_SECOND = 0.35;
+
+export const HtmlInCanvas2DBlur: React.FC = () => {
+ const frame = useCurrentFrame();
+ const {width, height, fps} = useVideoConfig();
+
+ const onPaint: HtmlInCanvasOnPaint = useCallback(
+ ({canvas, element, elementImage}) => {
+ const ctx = canvas.getContext('2d');
+ if (!ctx) {
+ throw new Error('Failed to acquire 2D context');
+ }
+
+ const t = (frame / fps) * Math.PI * 2 * BLUR_CYCLES_PER_SECOND;
+ const blurPx =
+ BLUR_MIN_PX +
+ (BLUR_MAX_PX - BLUR_MIN_PX) * (0.5 + 0.5 * Math.sin(t));
+
+ ctx.reset();
+ ctx.filter = `blur(${blurPx}px)`;
+ const transform = ctx.drawElementImage(elementImage, 0, 0);
+ element.style.transform = transform.toString();
+ },
+ [frame, fps],
+ );
+
+ return (
+ <HtmlInCanvas width={width} height={height} onPaint={onPaint}>
+ <AbsoluteFill
+ style={{
+ justifyContent: 'center',
+ alignItems: 'center',
+ backgroundColor: '#1a1a2e',
+ color: 'white',
+ fontSize: 120,
+ fontFamily: 'sans-serif',
+ }}
+ >
+ <h1 style={{margin: 0}}>Hello</h1>
+ </AbsoluteFill>
+ </HtmlInCanvas>
+ );
};
```
### WebGL
-Create the `webgl2` context, program, VAO, and texture in [`onInit`](#oninit). Each paint uploads the capture with [`texElementImage2D`](https://github.com/WICG/html-in-canvas) and draws a fullscreen triangle pair.
+Do all setup in [`onInit`](#oninit) such as getting the WebGL context and compiling the shader.
+`onInit` must return a cleanup function that destroys the resources that were created in `onInit`.
+
+Use [`texElementImage2D`](https://github.com/WICG/html-in-canvas) to turn the `elementImage` into a texture.
+
+<Demo type="html-in-canvas-webgl" />
<details>
<summary>This example is long. Expand to see it:</summary>
-```tsx title="WebGL2: minimal full component"
+```tsx twoslash title="WebGL2: minimal full component"
+/**
+ * Minimal WebGL2 + HtmlInCanvas sample (same code as /docs/remotion/html-in-canvas).
+ * UV wave distortion in the fragment shader (not expressible as a static CSS filter).
+ */
import React, {useCallback, useRef} from 'react';
import {
AbsoluteFill,
HtmlInCanvas,
HtmlInCanvasOnInit,
HtmlInCanvasOnPaint,
+ useCurrentFrame,
useVideoConfig,
} from 'remotion';
@@ -157,6 +208,7 @@ type GlState = {
gl: WebGL2RenderingContext;
program: WebGLProgram;
uTex: WebGLUniformLocation | null;
+ uTime: WebGLUniformLocation | null;
texture: WebGLTexture;
vao: WebGLVertexArrayObject;
};
@@ -173,13 +225,21 @@ void main() {
const FS = `#version 300 es
precision highp float;
uniform sampler2D u_tex;
+uniform float u_time;
in vec2 v_uv;
out vec4 o;
void main() {
- o = texture(u_tex, v_uv);
+ vec2 uv = v_uv;
+ uv.x += 0.045 * sin(v_uv.y * 32.0 + u_time * 5.0);
+ uv.y += 0.038 * sin(v_uv.x * 26.0 + u_time * 4.0);
+ o = texture(u_tex, uv);
}`;
-function linkProgram(gl: WebGL2RenderingContext, vsSrc: string, fsSrc: string) {
+function linkProgram(
+ gl: WebGL2RenderingContext,
+ vsSrc: string,
+ fsSrc: string,
+): WebGLProgram {
const vert = gl.createShader(gl.VERTEX_SHADER)!;
gl.shaderSource(vert, vsSrc);
gl.compileShader(vert);
@@ -199,8 +259,9 @@ 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,
]);
-export const WebGLExample: React.FC = () => {
- const {width, height} = useVideoConfig();
+export const HtmlInCanvasDocsMinimalWebGL: React.FC = () => {
+ const frame = useCurrentFrame();
+ const {width, height, fps} = useVideoConfig();
const gpuRef = useRef<GlState | null>(null);
const onInit: HtmlInCanvasOnInit = useCallback(({canvas}) => {
@@ -217,11 +278,14 @@ export const WebGLExample: React.FC = () => {
const program = linkProgram(gl, VS, FS);
const uTex = gl.getUniformLocation(program, 'u_tex');
+ const uTime = gl.getUniformLocation(program, 'u_time');
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);
@@ -236,7 +300,7 @@ export const WebGLExample: React.FC = () => {
gl.enableVertexAttribArray(locUv);
gl.vertexAttribPointer(locUv, 2, gl.FLOAT, false, 16, 8);
- gpuRef.current = {gl, program, uTex, texture, vao};
+ gpuRef.current = {gl, program, uTex, uTime, texture, vao};
return () => {
gl.deleteProgram(program);
@@ -247,37 +311,49 @@ export const WebGLExample: React.FC = () => {
};
}, []);
- const onPaint: HtmlInCanvasOnPaint = useCallback(({elementImage}) => {
- const gpu = gpuRef.current;
- if (!gpu) {
- 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.texElementImage2D(
- gl.TEXTURE_2D,
- 0,
- gl.RGBA,
- gl.RGBA,
- gl.UNSIGNED_BYTE,
- elementImage,
- );
-
- if (gpu.uTex) {
- gl.uniform1i(gpu.uTex, 0);
- }
-
- gl.bindVertexArray(gpu.vao);
- gl.drawArrays(gl.TRIANGLES, 0, 6);
- }, []);
+ const onPaint: HtmlInCanvasOnPaint = useCallback(
+ ({elementImage}) => {
+ const gpu = gpuRef.current;
+ if (!gpu) {
+ 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.texElementImage2D(
+ gl.TEXTURE_2D,
+ 0,
+ gl.RGBA,
+ gl.RGBA,
+ gl.UNSIGNED_BYTE,
+ elementImage,
+ );
+
+ if (gpu.uTex) {
+ gl.uniform1i(gpu.uTex, 0);
+ }
+
+ if (gpu.uTime) {
+ gl.uniform1f(gpu.uTime, frame / fps);
+ }
+
+ gl.bindVertexArray(gpu.vao);
+ gl.drawArrays(gl.TRIANGLES, 0, 6);
+ },
+ [frame, fps],
+ );
return (
- <HtmlInCanvas width={width} height={height} onInit={onInit} onPaint={onPaint}>
+ <HtmlInCanvas
+ width={width}
+ height={height}
+ onInit={onInit}
+ onPaint={onPaint}
+ >
<AbsoluteFill
style={{
justifyContent: 'center',
@@ -291,34 +367,92 @@ export const WebGLExample: React.FC = () => {
</HtmlInCanvas>
);
};
+
```
</details>
### WebGPU
-Request a device and configure the [`webgpu`](https://developer.mozilla.org/en-US/docs/Web/API/GPUCanvasContext) context in [`onInit`](#oninit). Each paint copies the element into a [`GPUTexture`](https://developer.mozilla.org/en-US/docs/Web/API/GPUTexture) with `copyElementImageToTexture`, then draws a fullscreen triangle to the swapchain.
+Use [`onInit`](#oninit) to get a WebGPU context, to request a GPU and to compile shaders.
+`onInit` must return a cleanup function that destroys the resources that were created in `onInit`.
+In `onPaint`, draw the `elementImage` to the canvas using `copyElementImageToTexture`.
+
+<Demo type="html-in-canvas-webgpu" />
<details>
<summary>This example is long. Expand to see it:</summary>
-```tsx title="WebGPU: minimal full component"
+```tsx twoslash title="compose-webgpu.tsx"
import React, {useCallback, useRef} from 'react';
import {
AbsoluteFill,
HtmlInCanvas,
- HtmlInCanvasOnInit,
- HtmlInCanvasOnPaint,
+ type HtmlInCanvasOnInit,
+ type HtmlInCanvasOnPaint,
+ useCurrentFrame,
useVideoConfig,
} from 'remotion';
-const WGSL = `
+// Minimal WebGPU types β€” `@webgpu/types` is intentionally not a dependency,
+// matching the convention in `packages/core/src/canvas-effects/gpu-device.ts`.
+type Gpu = {
+ requestAdapter(): Promise<GpuAdapter | null>;
+ getPreferredCanvasFormat(): string;
+};
+type GpuAdapter = {requestDevice(): Promise<GpuDevice>};
+type GpuTextureView = unknown;
+type GpuTexture = {createView(): GpuTextureView; destroy(): void};
+type GpuBuffer = {destroy(): void};
+type GpuBindGroup = unknown;
+type GpuPipeline = unknown;
+type GpuSampler = unknown;
+type GpuShaderModule = unknown;
+type GpuDevice = {
+ createShaderModule(d: {code: string}): GpuShaderModule;
+ createRenderPipeline(d: unknown): GpuPipeline;
+ createTexture(d: unknown): GpuTexture;
+ createSampler(d?: unknown): GpuSampler;
+ createBindGroup(d: unknown): GpuBindGroup;
+ createBuffer(d: unknown): GpuBuffer;
+ createCommandEncoder(): {
+ beginRenderPass(d: unknown): {
+ setPipeline(p: GpuPipeline): void;
+ setBindGroup(i: number, b: GpuBindGroup): void;
+ draw(n: number): void;
+ end(): void;
+ };
+ finish(): unknown;
+ };
+ queue: {
+ submit(c: unknown[]): void;
+ writeBuffer(b: GpuBuffer, offset: number, data: BufferSource): void;
+ copyElementImageToTexture(
+ source: Element | ElementImage,
+ width: number,
+ height: number,
+ destination: {texture: GpuTexture},
+ ): void;
+ };
+};
+type GpuCanvasContext = {
+ configure(d: {
+ device: GpuDevice;
+ format: string;
+ alphaMode: 'premultiplied' | 'opaque';
+ }): void;
+ getCurrentTexture(): GpuTexture;
+};
+
+const WGSL = /* wgsl */ `
struct VsOut {
@builtin(position) pos: vec4f,
@location(0) uv: vec2f,
-}
+};
+
@vertex
fn vs(@builtin(vertex_index) i: u32) -> VsOut {
+ // Fullscreen triangle (slightly oversized β€” clipped to viewport).
var p = array(vec2f(-1.0, -3.0), vec2f(-1.0, 1.0), vec2f(3.0, 1.0));
var uv = array(vec2f(0.0, 2.0), vec2f(0.0, 0.0), vec2f(2.0, 0.0));
var o: VsOut;
@@ -326,77 +460,148 @@ fn vs(@builtin(vertex_index) i: u32) -> VsOut {
o.uv = uv[i];
return o;
}
+
+struct U {
+ time: f32,
+ _pad: f32,
+ resolution: vec2f,
+};
+
@group(0) @binding(0) var samp: sampler;
@group(0) @binding(1) var tex: texture_2d<f32>;
+@group(0) @binding(2) var<uniform> u: U;
+
@fragment
fn fs(in: VsOut) -> @location(0) vec4f {
- return textureSample(tex, samp, in.uv);
+ // Animate pixel cell size with a slow breathing motion.
+ let cell = 6.0 + sin(u.time * 0.8) * 4.0;
+ let snapped = floor(in.uv * u.resolution / cell) * cell / u.resolution;
+
+ // Slight chromatic offset between channels β€” sampled from snapped centers.
+ let off = vec2f(2.0, 0.0) / u.resolution;
+ let r = textureSample(tex, samp, snapped + off).r;
+ let g = textureSample(tex, samp, snapped).g;
+ let b = textureSample(tex, samp, snapped - off).b;
+ let a = textureSample(tex, samp, snapped).a;
+
+ // Posterize to 5 levels per channel for a flatter, screenprint look.
+ let levels = 5.0;
+ let q = floor(vec3f(r, g, b) * levels) / (levels - 1.0);
+
+ return vec4f(q, a);
}
`;
type GpuState = {
- device: GPUDevice;
- context: GPUCanvasContext;
- pipeline: GPURenderPipeline;
- sampler: GPUSampler;
- texture: GPUTexture;
- bindGroup: GPUBindGroup;
+ device: GpuDevice;
+ context: GpuCanvasContext;
+ pipeline: GpuPipeline;
+ sampler: GpuSampler;
+ texture: GpuTexture;
+ uniformBuffer: GpuBuffer;
+ bindGroup: GpuBindGroup;
width: number;
height: number;
};
-export const WebGPUExample: React.FC = () => {
- const {width, height} = useVideoConfig();
+export const HtmlInCanvasComposeWebGPU: React.FC = () => {
+ const frame = useCurrentFrame();
+ const {width, height, fps} = useVideoConfig();
const gpuRef = useRef<GpuState | null>(null);
+ const time = frame / fps;
+
const onInit: HtmlInCanvasOnInit = useCallback(async ({canvas}) => {
- const gpuApi = navigator.gpu;
- if (!gpuApi) {
- throw new Error('WebGPU not available');
+ if (typeof navigator === 'undefined' || !('gpu' in navigator)) {
+ throw new Error('WebGPU is not available in this environment');
}
- const adapter = await gpuApi.requestAdapter();
+ const gpu = (navigator as unknown as {gpu: Gpu}).gpu;
+ const adapter = await gpu.requestAdapter();
if (!adapter) {
- throw new Error('No WebGPU adapter');
+ throw new Error('No WebGPU adapter available');
}
const device = await adapter.requestDevice();
- const context = canvas.getContext('webgpu');
+ const context = (
+ canvas as unknown as {
+ getContext(id: 'webgpu'): GpuCanvasContext | null;
+ }
+ ).getContext('webgpu');
if (!context) {
throw new Error('WebGPU context unavailable on OffscreenCanvas');
}
- const format = gpuApi.getPreferredCanvasFormat();
- context.configure({device, format, alphaMode: 'premultiplied'});
+ // Use the device's preferred swap-chain format (typically `bgra8unorm`)
+ // to avoid an extra format-conversion copy on present.
+ const presentationFormat = gpu.getPreferredCanvasFormat();
+
+ context.configure({
+ device,
+ format: presentationFormat,
+ alphaMode: 'premultiplied',
+ });
const module = device.createShaderModule({code: WGSL});
+
const pipeline = device.createRenderPipeline({
layout: 'auto',
vertex: {module, entryPoint: 'vs'},
fragment: {
module,
entryPoint: 'fs',
- targets: [{format}],
+ targets: [{format: presentationFormat}],
},
primitive: {topology: 'triangle-list'},
});
+ const TextureUsage = (
+ globalThis as unknown as {
+ GPUTextureUsage: {
+ COPY_DST: number;
+ TEXTURE_BINDING: number;
+ RENDER_ATTACHMENT: number;
+ };
+ }
+ ).GPUTextureUsage;
+ const BufferUsage = (
+ globalThis as unknown as {
+ GPUBufferUsage: {UNIFORM: number; COPY_DST: number};
+ }
+ ).GPUBufferUsage;
+
const texture = device.createTexture({
size: {width: canvas.width, height: canvas.height},
format: 'rgba8unorm',
- usage: GPUTextureUsage.COPY_DST | GPUTextureUsage.TEXTURE_BINDING,
+ usage:
+ TextureUsage.COPY_DST |
+ TextureUsage.TEXTURE_BINDING |
+ TextureUsage.RENDER_ATTACHMENT,
});
const sampler = device.createSampler({
magFilter: 'linear',
minFilter: 'linear',
+ addressModeU: 'clamp-to-edge',
+ addressModeV: 'clamp-to-edge',
+ });
+
+ // 16 bytes: time (f32), pad (f32), resolution (vec2f).
+ const uniformBuffer = device.createBuffer({
+ size: 16,
+ usage: BufferUsage.UNIFORM | BufferUsage.COPY_DST,
});
const bindGroup = device.createBindGroup({
- layout: pipeline.getBindGroupLayout(0),
+ layout: (
+ pipeline as unknown as {
+ getBindGroupLayout(i: number): unknown;
+ }
+ ).getBindGroupLayout(0),
entries: [
{binding: 0, resource: sampler},
{binding: 1, resource: texture.createView()},
+ {binding: 2, resource: {buffer: uniformBuffer}},
],
});
@@ -406,6 +611,7 @@ export const WebGPUExample: React.FC = () => {
pipeline,
sampler,
texture,
+ uniformBuffer,
bindGroup,
width: canvas.width,
height: canvas.height,
@@ -413,53 +619,80 @@ export const WebGPUExample: React.FC = () => {
return () => {
texture.destroy();
+ uniformBuffer.destroy();
gpuRef.current = null;
};
}, []);
- const onPaint: HtmlInCanvasOnPaint = useCallback(({elementImage}) => {
- const gpu = gpuRef.current;
- if (!gpu) {
- return;
- }
-
- const {device, context, pipeline, texture, bindGroup} = gpu;
-
- device.queue.copyElementImageToTexture(elementImage, gpu.width, gpu.height, {
- texture,
- });
-
- const encoder = device.createCommandEncoder();
- const view = context.getCurrentTexture().createView();
- const pass = encoder.beginRenderPass({
- colorAttachments: [
- {
- view,
- clearValue: {r: 0, g: 0, b: 0, a: 0},
- loadOp: 'clear',
- storeOp: 'store',
- },
- ],
- });
- pass.setPipeline(pipeline);
- pass.setBindGroup(0, bindGroup);
- pass.draw(3);
- pass.end();
- device.queue.submit([encoder.finish()]);
- }, []);
+ const onPaint: HtmlInCanvasOnPaint = useCallback(
+ ({elementImage}) => {
+ const gpu = gpuRef.current;
+ if (!gpu) {
+ return;
+ }
+
+ const {device, context, pipeline, texture, bindGroup, uniformBuffer} =
+ gpu;
+
+ device.queue.copyElementImageToTexture(
+ elementImage,
+ gpu.width,
+ gpu.height,
+ {texture},
+ );
+
+ const uniforms = new Float32Array([time, 0, gpu.width, gpu.height]);
+ device.queue.writeBuffer(uniformBuffer, 0, uniforms);
+
+ const encoder = device.createCommandEncoder();
+ const view = context.getCurrentTexture().createView();
+ const pass = encoder.beginRenderPass({
+ colorAttachments: [
+ {
+ view,
+ clearValue: {r: 0, g: 0, b: 0, a: 0},
+ loadOp: 'clear',
+ storeOp: 'store',
+ },
+ ],
+ });
+ pass.setPipeline(pipeline);
+ pass.setBindGroup(0, bindGroup);
+ pass.draw(3);
+ pass.end();
+ device.queue.submit([encoder.finish()]);
+ },
+ [time],
+ );
return (
- <HtmlInCanvas width={width} height={height} onInit={onInit} onPaint={onPaint}>
- <AbsoluteFill
- style={{
- justifyContent: 'center',
- alignItems: 'center',
- fontSize: 120,
- }}
+ <AbsoluteFill
+ style={{
+ justifyContent: 'center',
+ alignItems: 'center',
+ }}
+ >
+ <HtmlInCanvas
+ width={width}
+ height={height}
+ onInit={onInit}
+ onPaint={onPaint}
>
- <h1>Hello</h1>
- </AbsoluteFill>
- </HtmlInCanvas>
+ <AbsoluteFill
+ style={{
+ backgroundColor: 'white',
+ color: 'black',
+ justifyContent: 'center',
+ alignItems: 'center',
+ fontSize: 120,
+ fontFamily: 'sans-serif',
+ fontWeight: 'bold',
+ }}
+ >
+ <h1>Hello, World!</h1>
+ </AbsoluteFill>
+ </HtmlInCanvas>
+ </AbsoluteFill>
);
};
```
@@ -495,10 +728,6 @@ const onPaint: HtmlInCanvasOnPaint = async ({canvas, elementImage}) => {
};
```
-## Other props
-
-`<HtmlInCanvas>` accepts the same props as [`<Sequence layout="none">`](/docs/sequence#layout), including [`from`](/docs/sequence#from), [`durationInFrames`](/docs/sequence#durationinframes), [`name`](/docs/sequence#name), [`showInTimeline`](/docs/sequence#showintimeline), [`premountFor`](/docs/sequence#premountfor), [`postmountFor`](/docs/sequence#postmountfor), [`styleWhilePremounted`](/docs/sequence#stylewhilepremounted), [`className`](/docs/sequence#classname), and [`style`](/docs/sequence#style). The `styleWhilePostmounted` and `controls` props are also accepted, following the same shape as on [`<Sequence>`](/docs/sequence).
-
## Compatibility
<CompatibilityTable
@@ -515,7 +744,7 @@ const onPaint: HtmlInCanvasOnPaint = async ({canvas, elementImage}) => {
hideServers
/>
-The HTML-in-canvas feature itself depends on Chromium and enabled experimental APIs; see [HTML-in-canvas](/docs/client-side-rendering/html-in-canvas#compatibility).
+Only works in Chrome 149 and later with the flag enabled, as mentioned on the top of the page.
## See also
diff --git a/packages/docs/static/img/html-in-canvas-2d-blur.mp4 b/packages/docs/static/img/html-in-canvas-2d-blur.mp4
new file mode 100644
index 0000000000..99cb94fcb1
Binary files /dev/null and b/packages/docs/static/img/html-in-canvas-2d-blur.mp4 differ
diff --git a/packages/docs/static/img/html-in-canvas-webgl.mp4 b/packages/docs/static/img/html-in-canvas-webgl.mp4
new file mode 100644
index 0000000000..b70ef87827
Binary files /dev/null and b/packages/docs/static/img/html-in-canvas-webgl.mp4 differ
diff --git a/packages/docs/static/img/html-in-canvas-webgpu.mp4 b/packages/docs/static/img/html-in-canvas-webgpu.mp4
new file mode 100644
index 0000000000..50ffd15aca
Binary files /dev/null and b/packages/docs/static/img/html-in-canvas-webgpu.mp4 differ
diff --git a/packages/example/src/HtmlInCanvas/docs-demo-2d-blur.tsx b/packages/example/src/HtmlInCanvas/docs-demo-2d-blur.tsx
new file mode 100644
index 0000000000..b1076151e2
--- /dev/null
+++ b/packages/example/src/HtmlInCanvas/docs-demo-2d-blur.tsx
@@ -0,0 +1,60 @@
+import React, {useCallback} from 'react';
+import {
+ AbsoluteFill,
+ HtmlInCanvas,
+ type HtmlInCanvasOnPaint,
+ useCurrentFrame,
+ useVideoConfig,
+} from 'remotion';
+
+/** Pixels β€” blur oscillates between these bounds. */
+const BLUR_MIN_PX = 4;
+const BLUR_MAX_PX = 22;
+/** Blur animation speed (full sine cycles per second). */
+const BLUR_CYCLES_PER_SECOND = 0.35;
+
+/**
+ * 2D `ctx.filter` blur that varies with [`useCurrentFrame()`](/docs/use-current-frame), plus
+ * `drawElementImage` β€” see docs β€œonPaint examples β†’ 2D”.
+ * Composition id: `html-in-canvas-docs-demo-2d-blur`.
+ */
+export const HtmlInCanvasDocsDemo2DBlur: React.FC = () => {
+ const frame = useCurrentFrame();
+ const {width, height, fps} = useVideoConfig();
+
+ const onPaint: HtmlInCanvasOnPaint = useCallback(
+ ({canvas, element, elementImage}) => {
+ const ctx = canvas.getContext('2d');
+ if (!ctx) {
+ throw new Error('Failed to acquire 2D context');
+ }
+
+ const t = (frame / fps) * Math.PI * 2 * BLUR_CYCLES_PER_SECOND;
+ const blurPx =
+ BLUR_MIN_PX + (BLUR_MAX_PX - BLUR_MIN_PX) * (0.5 + 0.5 * Math.sin(t));
+
+ ctx.reset();
+ ctx.filter = `blur(${blurPx}px)`;
+ const transform = ctx.drawElementImage(elementImage, 0, 0);
+ element.style.transform = transform.toString();
+ },
+ [frame, fps],
+ );
+
+ return (
+ <HtmlInCanvas width={width} height={height} onPaint={onPaint}>
+ <AbsoluteFill
+ style={{
+ justifyContent: 'center',
+ alignItems: 'center',
+ backgroundColor: '#1a1a2e',
+ color: 'white',
+ fontSize: 120,
+ fontFamily: 'sans-serif',
+ }}
+ >
+ <h1 style={{margin: 0}}>Hello</h1>
+ </AbsoluteFill>
+ </HtmlInCanvas>
+ );
+};
diff --git a/packages/example/src/HtmlInCanvas/index.tsx b/packages/example/src/HtmlInCanvas/index.tsx
index 2c0f823ea1..2b45bec6da 100644
--- a/packages/example/src/HtmlInCanvas/index.tsx
+++ b/packages/example/src/HtmlInCanvas/index.tsx
@@ -1,5 +1,6 @@
export {HtmlInCanvasComplexText} from './complex-text';
export {HtmlInCanvasComposeAsyncBitmap} from './compose-async-bitmap';
+export {HtmlInCanvasDocsDemo2DBlur} from './docs-demo-2d-blur';
export {HtmlInCanvasDocsMinimalWebGL} from './minimal-docs-webgl';
export {HtmlInCanvasDocsMinimalWebGPU} from './minimal-docs-webgpu';
export {HtmlInCanvasComposeWebGL} from './compose-webgl';
diff --git a/packages/example/src/HtmlInCanvas/minimal-docs-webgl.tsx b/packages/example/src/HtmlInCanvas/minimal-docs-webgl.tsx
index 7ae03b33b4..74107c998c 100644
--- a/packages/example/src/HtmlInCanvas/minimal-docs-webgl.tsx
+++ b/packages/example/src/HtmlInCanvas/minimal-docs-webgl.tsx
@@ -1,5 +1,6 @@
/**
* Minimal WebGL2 + HtmlInCanvas sample (same code as /docs/remotion/html-in-canvas).
+ * UV wave distortion in the fragment shader (not expressible as a static CSS filter).
*/
import React, {useCallback, useRef} from 'react';
import {
@@ -7,6 +8,7 @@ import {
HtmlInCanvas,
HtmlInCanvasOnInit,
HtmlInCanvasOnPaint,
+ useCurrentFrame,
useVideoConfig,
} from 'remotion';
@@ -14,6 +16,7 @@ type GlState = {
gl: WebGL2RenderingContext;
program: WebGLProgram;
uTex: WebGLUniformLocation | null;
+ uTime: WebGLUniformLocation | null;
texture: WebGLTexture;
vao: WebGLVertexArrayObject;
};
@@ -30,10 +33,14 @@ void main() {
const FS = `#version 300 es
precision highp float;
uniform sampler2D u_tex;
+uniform float u_time;
in vec2 v_uv;
out vec4 o;
void main() {
- o = texture(u_tex, v_uv);
+ vec2 uv = v_uv;
+ uv.x += 0.045 * sin(v_uv.y * 32.0 + u_time * 5.0);
+ uv.y += 0.038 * sin(v_uv.x * 26.0 + u_time * 4.0);
+ o = texture(u_tex, uv);
}`;
function linkProgram(
@@ -61,7 +68,8 @@ const QUAD = new Float32Array([
]);
export const HtmlInCanvasDocsMinimalWebGL: React.FC = () => {
- const {width, height} = useVideoConfig();
+ const frame = useCurrentFrame();
+ const {width, height, fps} = useVideoConfig();
const gpuRef = useRef<GlState | null>(null);
const onInit: HtmlInCanvasOnInit = useCallback(({canvas}) => {
@@ -78,11 +86,14 @@ export const HtmlInCanvasDocsMinimalWebGL: React.FC = () => {
const program = linkProgram(gl, VS, FS);
const uTex = gl.getUniformLocation(program, 'u_tex');
+ const uTime = gl.getUniformLocation(program, 'u_time');
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);
@@ -97,7 +108,7 @@ export const HtmlInCanvasDocsMinimalWebGL: React.FC = () => {
gl.enableVertexAttribArray(locUv);
gl.vertexAttribPointer(locUv, 2, gl.FLOAT, false, 16, 8);
- gpuRef.current = {gl, program, uTex, texture, vao};
+ gpuRef.current = {gl, program, uTex, uTime, texture, vao};
return () => {
gl.deleteProgram(program);
@@ -108,34 +119,41 @@ export const HtmlInCanvasDocsMinimalWebGL: React.FC = () => {
};
}, []);
- const onPaint: HtmlInCanvasOnPaint = useCallback(({elementImage}) => {
- const gpu = gpuRef.current;
- if (!gpu) {
- 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.texElementImage2D(
- gl.TEXTURE_2D,
- 0,
- gl.RGBA,
- gl.RGBA,
- gl.UNSIGNED_BYTE,
- elementImage,
- );
-
- if (gpu.uTex) {
- gl.uniform1i(gpu.uTex, 0);
- }
-
- gl.bindVertexArray(gpu.vao);
- gl.drawArrays(gl.TRIANGLES, 0, 6);
- }, []);
+ const onPaint: HtmlInCanvasOnPaint = useCallback(
+ ({elementImage}) => {
+ const gpu = gpuRef.current;
+ if (!gpu) {
+ 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.texElementImage2D(
+ gl.TEXTURE_2D,
+ 0,
+ gl.RGBA,
+ gl.RGBA,
+ gl.UNSIGNED_BYTE,
+ elementImage,
+ );
+
+ if (gpu.uTex) {
+ gl.uniform1i(gpu.uTex, 0);
+ }
+
+ if (gpu.uTime) {
+ gl.uniform1f(gpu.uTime, frame / fps);
+ }
+
+ gl.bindVertexArray(gpu.vao);
+ gl.drawArrays(gl.TRIANGLES, 0, 6);
+ },
+ [frame, fps],
+ );
return (
<HtmlInCanvas
diff --git a/packages/example/src/HtmlInCanvas/minimal-docs-webgpu.tsx b/packages/example/src/HtmlInCanvas/minimal-docs-webgpu.tsx
index f886e3d2ad..9c605c0aed 100644
--- a/packages/example/src/HtmlInCanvas/minimal-docs-webgpu.tsx
+++ b/packages/example/src/HtmlInCanvas/minimal-docs-webgpu.tsx
@@ -1,205 +1,6 @@
/**
- * Minimal WebGPU + HtmlInCanvas sample (same code as /docs/remotion/html-in-canvas).
+ * Intentionally identical to {@link HtmlInCanvasComposeWebGPU} β€” that file is
+ * the canonical WebGPU + HtmlInCanvas sample (correct swap-chain format, texture
+ * usage, uniforms). Re-exported under this name for docs / Studio (`html-in-canvas-docs-minimal-webgpu`).
*/
-import React, {useCallback, useRef} from 'react';
-import {
- AbsoluteFill,
- HtmlInCanvas,
- HtmlInCanvasOnInit,
- HtmlInCanvasOnPaint,
- useVideoConfig,
-} from 'remotion';
-
-// Narrow types so `OffscreenCanvas#getContext('webgpu')` and
-// `GPUQueue#copyElementImageToTexture` typecheck (see compose-webgpu.tsx).
-type GpuCanvasContext = {
- configure(d: {
- device: GPUDevice;
- format: string;
- alphaMode: 'premultiplied' | 'opaque';
- }): void;
- getCurrentTexture(): GPUTexture;
-};
-
-type GpuNavigator = {
- requestAdapter(): Promise<GPUAdapter | null>;
- getPreferredCanvasFormat(): string;
-};
-
-const WGSL = `
-struct VsOut {
- @builtin(position) pos: vec4f,
- @location(0) uv: vec2f,
-}
-@vertex
-fn vs(@builtin(vertex_index) i: u32) -> VsOut {
- var p = array(vec2f(-1.0, -3.0), vec2f(-1.0, 1.0), vec2f(3.0, 1.0));
- var uv = array(vec2f(0.0, 2.0), vec2f(0.0, 0.0), vec2f(2.0, 0.0));
- var o: VsOut;
- o.pos = vec4f(p[i], 0.0, 1.0);
- o.uv = uv[i];
- return o;
-}
-@group(0) @binding(0) var samp: sampler;
-@group(0) @binding(1) var tex: texture_2d<f32>;
-@fragment
-fn fs(in: VsOut) -> @location(0) vec4f {
- return textureSample(tex, samp, in.uv);
-}
-`;
-
-type GpuState = {
- device: GPUDevice;
- context: GpuCanvasContext;
- pipeline: GPURenderPipeline;
- sampler: GPUSampler;
- texture: GPUTexture;
- bindGroup: GPUBindGroup;
- width: number;
- height: number;
-};
-
-export const HtmlInCanvasDocsMinimalWebGPU: React.FC = () => {
- const {width, height} = useVideoConfig();
- const gpuRef = useRef<GpuState | null>(null);
-
- const onInit: HtmlInCanvasOnInit = useCallback(async ({canvas}) => {
- if (typeof navigator === 'undefined' || !('gpu' in navigator)) {
- throw new Error('WebGPU not available');
- }
-
- const gpuApi = (navigator as unknown as {gpu: GpuNavigator}).gpu;
- const adapter = await gpuApi.requestAdapter();
- if (!adapter) {
- throw new Error('No WebGPU adapter');
- }
-
- const device = await adapter.requestDevice();
- const context = (
- canvas as unknown as {
- getContext(id: 'webgpu'): GpuCanvasContext | null;
- }
- ).getContext('webgpu');
- if (!context) {
- throw new Error('WebGPU context unavailable on OffscreenCanvas');
- }
-
- const format = gpuApi.getPreferredCanvasFormat() as GPUTextureFormat;
- context.configure({device, format, alphaMode: 'premultiplied'});
-
- const module = device.createShaderModule({code: WGSL});
- const pipeline = device.createRenderPipeline({
- layout: 'auto',
- vertex: {module, entryPoint: 'vs'},
- fragment: {
- module,
- entryPoint: 'fs',
- targets: [{format}] as GPUColorTargetState[],
- },
- primitive: {topology: 'triangle-list'},
- });
-
- const TextureUsage = (
- globalThis as unknown as {
- GPUTextureUsage: {COPY_DST: number; TEXTURE_BINDING: number};
- }
- ).GPUTextureUsage;
-
- const texture = device.createTexture({
- size: {width: canvas.width, height: canvas.height},
- format: 'rgba8unorm',
- usage: TextureUsage.COPY_DST | TextureUsage.TEXTURE_BINDING,
- });
-
- const sampler = device.createSampler({
- magFilter: 'linear',
- minFilter: 'linear',
- });
-
- const bindGroup = device.createBindGroup({
- layout: (
- pipeline as unknown as {
- getBindGroupLayout(i: number): GPUBindGroupLayout;
- }
- ).getBindGroupLayout(0),
- entries: [
- {binding: 0, resource: sampler},
- {binding: 1, resource: texture.createView()},
- ],
- });
-
- gpuRef.current = {
- device,
- context,
- pipeline,
- sampler,
- texture,
- bindGroup,
- width: canvas.width,
- height: canvas.height,
- };
-
- return () => {
- texture.destroy();
- gpuRef.current = null;
- };
- }, []);
-
- const onPaint: HtmlInCanvasOnPaint = useCallback(({elementImage}) => {
- const gpu = gpuRef.current;
- if (!gpu) {
- return;
- }
-
- const {device, context, pipeline, texture, bindGroup} = gpu;
-
- const queue = device.queue as unknown as {
- copyElementImageToTexture(
- source: unknown,
- width: number,
- height: number,
- destination: {texture: GPUTexture},
- ): void;
- };
- queue.copyElementImageToTexture(elementImage, gpu.width, gpu.height, {
- texture,
- });
-
- const encoder = device.createCommandEncoder();
- const view = context.getCurrentTexture().createView();
- const pass = encoder.beginRenderPass({
- colorAttachments: [
- {
- view,
- clearValue: {r: 0, g: 0, b: 0, a: 0},
- loadOp: 'clear',
- storeOp: 'store',
- },
- ],
- });
- pass.setPipeline(pipeline);
- pass.setBindGroup(0, bindGroup);
- pass.draw(3);
- pass.end();
- device.queue.submit([encoder.finish()]);
- }, []);
-
- return (
- <HtmlInCanvas
- width={width}
- height={height}
- onInit={onInit}
- onPaint={onPaint}
- >
- <AbsoluteFill
- style={{
- justifyContent: 'center',
- alignItems: 'center',
- fontSize: 120,
- }}
- >
- <h1>Hello</h1>
- </AbsoluteFill>
- </HtmlInCanvas>
- );
-};
+export {HtmlInCanvasComposeWebGPU as HtmlInCanvasDocsMinimalWebGPU} from './compose-webgpu';
diff --git a/packages/example/src/Root.tsx b/packages/example/src/Root.tsx
index 299af25216..a2b896b2fb 100644
--- a/packages/example/src/Root.tsx
+++ b/packages/example/src/Root.tsx
@@ -51,6 +51,7 @@ import {
HtmlInCanvasComposeWebGPU,
HtmlInCanvasDocsMinimalWebGL,
HtmlInCanvasDocsMinimalWebGPU,
+ HtmlInCanvasDocsDemo2DBlur,
HtmlInCanvasDemo,
HtmlInCanvasPrivacy,
HtmlInCanvasReactSvg,
@@ -946,6 +947,14 @@ export const Index: React.FC = () => {
width={1920}
durationInFrames={120}
/>
+ <Composition
+ id="html-in-canvas-docs-demo-2d-blur"
+ component={HtmlInCanvasDocsDemo2DBlur}
+ fps={30}
+ height={1080}
+ width={1920}
+ durationInFrames={120}
+ />
<Composition
id="html-in-canvas-complex-text"
component={HtmlInCanvasComplexText}