Skip to content

πŸŽ₯ Make videos programmatically with React

`remotion`: Add `pixelDensity` prop to HtmlInCanvas (#8088)

Jonny Burger5a10d20463fa
diff --git a/packages/core/src/HtmlInCanvas.tsx b/packages/core/src/HtmlInCanvas.tsx
index 15f4de921d..fc85cbbaa8 100644
--- a/packages/core/src/HtmlInCanvas.tsx
+++ b/packages/core/src/HtmlInCanvas.tsx
@@ -185,6 +185,7 @@ export type HtmlInCanvasOnPaintParams = {
readonly canvas: OffscreenCanvas;
readonly element: HTMLDivElement;
readonly elementImage: ElementImage;
+ readonly pixelDensity: number;
};
// Memoize the support check across the session β€” neither the platform
@@ -225,6 +226,8 @@ export type HtmlInCanvasOnInit = (
params: HtmlInCanvasOnPaintParams,
) => HtmlInCanvasOnInitCleanup | Promise<HtmlInCanvasOnInitCleanup>;
+export type HtmlInCanvasPixelDensity = number;
+
function assertHtmlInCanvasDimensions(width: unknown, height: unknown): void {
if (typeof width !== 'number' || typeof height !== 'number') {
throw new Error(
@@ -245,6 +248,44 @@ function assertHtmlInCanvasDimensions(width: unknown, height: unknown): void {
}
}
+function resolveHtmlInCanvasPixelDensity(
+ pixelDensity: HtmlInCanvasPixelDensity | undefined,
+): number {
+ if (pixelDensity === undefined) {
+ return 1;
+ }
+
+ if (
+ typeof pixelDensity !== 'number' ||
+ !Number.isFinite(pixelDensity) ||
+ pixelDensity <= 0
+ ) {
+ throw new Error(
+ `HtmlInCanvas: \`pixelDensity\` must be a positive finite number. Received: ${String(pixelDensity)}.`,
+ );
+ }
+
+ return pixelDensity;
+}
+
+const resizeOffscreenCanvas = ({
+ offscreen,
+ width,
+ height,
+}: {
+ offscreen: OffscreenCanvas;
+ width: number;
+ height: number;
+}) => {
+ if (offscreen.width !== width) {
+ offscreen.width = width;
+ }
+
+ if (offscreen.height !== height) {
+ offscreen.height = height;
+ }
+};
+
const defaultOnPaint: HtmlInCanvasOnPaint = ({
canvas,
element,
@@ -284,6 +325,7 @@ export type HtmlInCanvasProps = Omit<
readonly children: React.ReactNode;
readonly onPaint?: HtmlInCanvasOnPaint;
readonly onInit?: HtmlInCanvasOnInit;
+ readonly pixelDensity?: HtmlInCanvasPixelDensity;
};
/* eslint-enable react/require-default-props */
@@ -296,6 +338,7 @@ type HtmlInCanvasContentProps = {
readonly children: React.ReactNode;
readonly onPaint: HtmlInCanvasOnPaint | undefined;
readonly onInit: HtmlInCanvasOnInit | undefined;
+ readonly pixelDensity: HtmlInCanvasPixelDensity | undefined;
readonly controls: SequenceControls | undefined;
readonly style: React.CSSProperties | undefined;
};
@@ -305,7 +348,17 @@ const HtmlInCanvasContent = forwardRef<
HtmlInCanvasContentProps
>(
(
- {width, height, effects, children, onPaint, onInit, controls, style},
+ {
+ width,
+ height,
+ effects,
+ children,
+ onPaint,
+ onInit,
+ pixelDensity,
+ controls,
+ style,
+ },
ref,
) => {
const isInsideAncestorHtmlInCanvas = useContext(
@@ -313,6 +366,9 @@ const HtmlInCanvasContent = forwardRef<
);
assertHtmlInCanvasDimensions(width, height);
+ const resolvedPixelDensity = resolveHtmlInCanvasPixelDensity(pixelDensity);
+ const canvasWidth = Math.ceil(width * resolvedPixelDensity);
+ const canvasHeight = Math.ceil(height * resolvedPixelDensity);
const {continueRender, cancelRender} = useDelayRender();
if (!isHtmlInCanvasSupported()) {
@@ -322,7 +378,7 @@ const HtmlInCanvasContent = forwardRef<
const canvas2dRef = useRef<HTMLCanvasElement | null>(null);
const offscreenRef = useRef<OffscreenCanvas | null>(null);
const divRef = useRef<HTMLDivElement | null>(null);
- const canvasSizeKey = `${width}x${height}`;
+ const canvasSizeKey = `${width}x${height}@${resolvedPixelDensity}`;
const setLayoutCanvasRef = useCallback(
(node: HTMLCanvasElement | null) => {
@@ -369,8 +425,11 @@ const HtmlInCanvasContent = forwardRef<
);
}
- offscreen.width = width;
- offscreen.height = height;
+ resizeOffscreenCanvas({
+ offscreen,
+ width: canvasWidth,
+ height: canvasHeight,
+ });
try {
const placeholderCanvas = canvas2dRef.current;
@@ -404,6 +463,7 @@ const HtmlInCanvasContent = forwardRef<
canvas: offscreen,
element,
elementImage: initImage!,
+ pixelDensity: resolvedPixelDensity,
});
if (typeof cleanup !== 'function') {
throw new Error(
@@ -426,22 +486,30 @@ const HtmlInCanvasContent = forwardRef<
canvas: offscreen,
element,
elementImage: elImage!,
+ pixelDensity: resolvedPixelDensity,
});
await runEffectChain({
- state: chainState.get(width, height)!,
+ state: chainState.get(canvasWidth, canvasHeight)!,
source: offscreen,
effects: effectsRef.current,
output: offscreen,
- width,
- height,
+ width: canvasWidth,
+ height: canvasHeight,
});
continueRender(handle);
} catch (error) {
cancelRender(error);
}
- }, [chainState, continueRender, cancelRender, width, height]);
+ }, [
+ canvasHeight,
+ canvasWidth,
+ chainState,
+ continueRender,
+ cancelRender,
+ resolvedPixelDensity,
+ ]);
// Transfer control once per layout canvas instance, then listen for paint on
// the placeholder (capture) while drawing on the linked offscreen surface.
@@ -455,8 +523,11 @@ const HtmlInCanvasContent = forwardRef<
const offscreen = placeholder.transferControlToOffscreen();
offscreenRef.current = offscreen;
- offscreen.width = width;
- offscreen.height = height;
+ resizeOffscreenCanvas({
+ offscreen,
+ width: canvasWidth,
+ height: canvasHeight,
+ });
initializedRef.current = false;
unmountedRef.current = false;
@@ -471,7 +542,7 @@ const HtmlInCanvasContent = forwardRef<
onInitCleanupRef.current?.();
onInitCleanupRef.current = null;
};
- }, [onPaintCb, cancelRender, width, height]);
+ }, [onPaintCb, cancelRender, canvasWidth, canvasHeight]);
const onPaintChangedRef = useRef(false);
useLayoutEffect(() => {
@@ -515,6 +586,14 @@ const HtmlInCanvasContent = forwardRef<
};
}, [width, height]);
+ const canvasStyle = useMemo(() => {
+ return {
+ width,
+ height,
+ ...(style ?? {}),
+ };
+ }, [height, style, width]);
+
if (isInsideAncestorHtmlInCanvas) {
throw new Error(
'<HtmlInCanvas> effects cannot be nested together. Chrome will only display the outer effect. Consider merging the effects into one if you can.',
@@ -526,9 +605,9 @@ const HtmlInCanvasContent = forwardRef<
<canvas
key={canvasSizeKey}
ref={setLayoutCanvasRef}
- width={width}
- height={height}
- style={style}
+ width={canvasWidth}
+ height={canvasHeight}
+ style={canvasStyle}
>
<div ref={divRef} style={innerStyle}>
{children}
@@ -555,6 +634,7 @@ const HtmlInCanvasInner = forwardRef<
children,
onPaint,
onInit,
+ pixelDensity,
_experimentalControls: controls,
style,
durationInFrames,
@@ -603,6 +683,7 @@ const HtmlInCanvasInner = forwardRef<
effects={effects}
onPaint={onPaint}
onInit={onInit}
+ pixelDensity={pixelDensity}
controls={controls}
style={style}
>
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 21a6f56ec3..792fec5d1f 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -156,6 +156,7 @@ export {
type HtmlInCanvasOnInit,
type HtmlInCanvasOnInitCleanup,
type HtmlInCanvasOnPaint,
+ type HtmlInCanvasPixelDensity,
} from './HtmlInCanvas.js';
export type {
HtmlInCanvasOnPaintParams,
diff --git a/packages/core/src/test/html-in-canvas.test.tsx b/packages/core/src/test/html-in-canvas.test.tsx
index 49f8c472dc..712c03ab56 100644
--- a/packages/core/src/test/html-in-canvas.test.tsx
+++ b/packages/core/src/test/html-in-canvas.test.tsx
@@ -2,6 +2,7 @@ import {afterEach, expect, test} from 'bun:test';
import {cleanup, render, waitFor} from '@testing-library/react';
import React, {useCallback, useMemo} from 'react';
import type {TSequence} from '../CompositionManager.js';
+import type {HtmlInCanvasOnPaintParams} from '../HtmlInCanvas.js';
import {HtmlInCanvas} from '../HtmlInCanvas.js';
import {Internals} from '../internals.js';
import type {SequenceManagerContext} from '../SequenceManager.js';
@@ -13,18 +14,57 @@ import {
} from '../SequenceManager.js';
import {WrapSequenceContext} from './wrap-sequence-context.js';
-const stub2dContext = () => ({
- canvas: null as unknown as HTMLCanvasElement,
- reset: () => undefined,
- drawElementImage: () => new DOMMatrix(),
- getImageData: () => ({
- data: new Uint8ClampedArray(4),
- width: 1,
- height: 1,
- }),
- putImageData: () => undefined,
+class TestDOMMatrix {
+ private readonly scaleX: number;
+ private readonly scaleY: number;
+
+ public constructor(scaleX = 1, scaleY = 1) {
+ this.scaleX = scaleX;
+ this.scaleY = scaleY;
+ }
+
+ public scale(x: number, y: number) {
+ return new TestDOMMatrix(this.scaleX * x, this.scaleY * y);
+ }
+
+ public multiply(other: TestDOMMatrix) {
+ return new TestDOMMatrix(
+ this.scaleX * other.scaleX,
+ this.scaleY * other.scaleY,
+ );
+ }
+
+ public toString() {
+ return `matrix(${this.scaleX}, 0, 0, ${this.scaleY}, 0, 0)`;
+ }
+}
+
+Object.defineProperty(globalThis, 'DOMMatrix', {
+ configurable: true,
+ value: TestDOMMatrix,
});
+const stub2dContext = () => {
+ let currentTransform = new DOMMatrix();
+
+ return {
+ canvas: null as unknown as HTMLCanvasElement,
+ reset: () => {
+ currentTransform = new DOMMatrix();
+ },
+ scale: (x: number, y: number) => {
+ currentTransform = currentTransform.scale(x, y);
+ },
+ drawElementImage: () => currentTransform,
+ getImageData: () => ({
+ data: new Uint8ClampedArray(4),
+ width: 1,
+ height: 1,
+ }),
+ putImageData: () => undefined,
+ };
+};
+
Object.defineProperties(HTMLCanvasElement.prototype, {
getContext: {
configurable: true,
@@ -220,3 +260,73 @@ test('<HtmlInCanvas> keeps refs current when the canvas remounts', async () => {
expect(canvasRef.current).toBe(nextCanvas);
expect(registeredSequences[0]?.refForOutline?.current).toBe(nextCanvas);
});
+
+test('<HtmlInCanvas> can use a higher backing density', async () => {
+ let paintParams: HtmlInCanvasOnPaintParams | undefined;
+
+ const {container} = render(
+ <SequenceTestWrapper onRegisterSequence={() => undefined}>
+ <HtmlInCanvas
+ width={50}
+ height={50}
+ pixelDensity={2}
+ onPaint={(params) => {
+ paintParams = params;
+ }}
+ >
+ <div>Test</div>
+ </HtmlInCanvas>
+ </SequenceTestWrapper>,
+ );
+
+ await waitFor(() => {
+ expect(container.querySelector('canvas')?.getAttribute('width')).toBe(
+ '100',
+ );
+ });
+
+ const canvas = container.querySelector('canvas')!;
+ expect(canvas.getAttribute('height')).toBe('100');
+ expect(canvas.style.width).toBe('50px');
+ expect(canvas.style.height).toBe('50px');
+
+ canvas.dispatchEvent(new Event('paint'));
+
+ await waitFor(() => {
+ expect(paintParams).not.toBeUndefined();
+ });
+
+ if (!paintParams) {
+ throw new Error('Expected paint params to be captured');
+ }
+
+ expect(paintParams.canvas.width).toBe(100);
+ expect(paintParams.canvas.height).toBe(100);
+ expect(paintParams.pixelDensity).toBe(2);
+});
+
+test('<HtmlInCanvas> does not apply pixel density to the live DOM transform', async () => {
+ const {container} = render(
+ <SequenceTestWrapper onRegisterSequence={() => undefined}>
+ <HtmlInCanvas width={50} height={50} pixelDensity={2}>
+ <div>Test</div>
+ </HtmlInCanvas>
+ </SequenceTestWrapper>,
+ );
+
+ await waitFor(() => {
+ expect(container.querySelector('canvas')?.getAttribute('width')).toBe(
+ '100',
+ );
+ });
+
+ const canvas = container.querySelector('canvas')!;
+ canvas.dispatchEvent(new Event('paint'));
+
+ const htmlInCanvasElement = canvas.querySelector('div');
+ await waitFor(() => {
+ expect(htmlInCanvasElement?.style.transform).toBe(
+ new DOMMatrix().toString(),
+ );
+ });
+});
diff --git a/packages/docs/docs/remotion/html-in-canvas.mdx b/packages/docs/docs/remotion/html-in-canvas.mdx
index 0ddc71d4c7..76aca2c59d 100644
--- a/packages/docs/docs/remotion/html-in-canvas.mdx
+++ b/packages/docs/docs/remotion/html-in-canvas.mdx
@@ -66,11 +66,19 @@ See [`Config.setChromiumOpenGlRenderer()`](/docs/config#setchromiumopenglrendere
### `width`
-Width of the canvas and the inner layout area, in pixels. Must be a positive integer.
+Logical width of the canvas and the inner layout area, in pixels. Must be a positive integer.
### `height`
-Height of the canvas and the inner layout area, in pixels. Must be a positive integer.
+Logical height of the canvas and the inner layout area, in pixels. Must be a positive integer.
+
+### `pixelDensity?`<AvailableFrom v="4.0.472" />
+
+_number_
+
+Controls the backing bitmap density. Default: `1`.
+
+Set a higher value to paint to a higher-resolution backing canvas while keeping the logical canvas size unchanged.
### `children`
@@ -86,19 +94,19 @@ Do not nest `<HtmlInCanvas>` inside another `<HtmlInCanvas>`. Nesting is not sup
### `onPaint?`
Called when the children are updated and can be painted onto the canvas.
-If this callback is omitted, the children are painted using a `2d` context with no transform.
+If this callback is omitted, the children are painted using a `2d` context.
```tsx twoslash title="Simple example"
import {HtmlInCanvasOnPaint} from 'remotion';
-const onPaint: HtmlInCanvasOnPaint = ({canvas, element, elementImage}) => {
+const onPaint: HtmlInCanvasOnPaint = ({canvas, element, elementImage, pixelDensity}) => {
const ctx = canvas.getContext('2d');
if (!ctx) {
throw new Error('Failed to acquire 2D context');
}
ctx.reset();
- ctx.filter = 'blur(10px)';
+ ctx.filter = `blur(${10 * pixelDensity}px)`;
const transform = ctx.drawElementImage(elementImage, 0, 0);
element.style.transform = transform.toString();
};
@@ -110,7 +118,7 @@ The callback receives:
#### `canvas`
-An [`OffscreenCanvas`](https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCanvas) with dimensions `width` Γ— `height`.
+An [`OffscreenCanvas`](https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCanvas) with backing dimensions `width * pixelDensity` Γ— `height * pixelDensity`, rounded up.
You should paint to this canvas.
#### `element`
@@ -123,6 +131,10 @@ You should apply the return value of [`drawElementImage`](https://github.com/WIC
An [`ElementImage`](https://github.com/WICG/html-in-canvas#idl-changes) handle for the current capture.
You should paint this image to the canvas.
+#### `pixelDensity`
+
+The resolved pixel density. It is `1` by default, or the number passed to `pixelDensity`.
+
### `onInit?`
Runs once before the first paint. Use it to create GPU contexts or other resources tied to the [`OffscreenCanvas`](https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCanvas). Must return a cleanup function, or a `Promise` that resolves to one. The cleanup runs on unmount.
@@ -189,7 +201,7 @@ export const HtmlInCanvas2DBlur: React.FC = () => {
const {width, height, fps} = useVideoConfig();
const onPaint: HtmlInCanvasOnPaint = useCallback(
- ({canvas, element, elementImage}) => {
+ ({canvas, element, elementImage, pixelDensity}) => {
const ctx = canvas.getContext('2d');
if (!ctx) {
throw new Error('Failed to acquire 2D context');
@@ -201,7 +213,7 @@ export const HtmlInCanvas2DBlur: React.FC = () => {
(BLUR_MAX_PX - BLUR_MIN_PX) * (0.5 + 0.5 * Math.sin(t));
ctx.reset();
- ctx.filter = `blur(${blurPx}px)`;
+ ctx.filter = `blur(${blurPx * pixelDensity}px)`;
const transform = ctx.drawElementImage(elementImage, 0, 0);
element.style.transform = transform.toString();
},
diff --git a/packages/example/src/HtmlInCanvas/index.tsx b/packages/example/src/HtmlInCanvas/index.tsx
index 2133dc0f9a..6e1c4734a3 100644
--- a/packages/example/src/HtmlInCanvas/index.tsx
+++ b/packages/example/src/HtmlInCanvas/index.tsx
@@ -34,6 +34,7 @@ export {
} from './linear-blur-doc';
export {HtmlInCanvasDocsMinimalWebGL} from './minimal-docs-webgl';
export {HtmlInCanvasDocsMinimalWebGPU} from './minimal-docs-webgpu';
+export {HtmlInCanvasPixelDensity} from './pixel-density';
export {HtmlInCanvasPrivacy} from './privacy';
export {HtmlInCanvasReactSvg} from './react-svg';
export {RippleTransitionDoc, RippleTransitionDocThumb} from './ripple-doc';
diff --git a/packages/example/src/HtmlInCanvas/pixel-density.tsx b/packages/example/src/HtmlInCanvas/pixel-density.tsx
new file mode 100644
index 0000000000..caca372e5c
--- /dev/null
+++ b/packages/example/src/HtmlInCanvas/pixel-density.tsx
@@ -0,0 +1,66 @@
+import React from 'react';
+import {AbsoluteFill, HtmlInCanvas} from 'remotion';
+
+const Tile: React.FC<{
+ readonly label: string;
+ readonly pixelDensity: number;
+}> = ({label, pixelDensity}) => {
+ return (
+ <div style={{display: 'flex', flexDirection: 'column', gap: 6}}>
+ <HtmlInCanvas
+ width={50}
+ height={50}
+ pixelDensity={pixelDensity}
+ style={{
+ borderRadius: 10,
+ overflow: 'hidden',
+ }}
+ >
+ <div
+ style={{
+ width: 50,
+ height: 50,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ background: 'linear-gradient(135deg, #00d4ff, #7c3aed)',
+ color: 'white',
+ fontFamily: 'sans-serif',
+ fontSize: 14,
+ fontWeight: 700,
+ }}
+ >
+ Hi
+ </div>
+ </HtmlInCanvas>
+ <div
+ style={{
+ color: 'white',
+ fontFamily: 'sans-serif',
+ fontSize: 9,
+ textAlign: 'center',
+ }}
+ >
+ {label}
+ </div>
+ </div>
+ );
+};
+
+export const HtmlInCanvasPixelDensity: React.FC = () => {
+ return (
+ <AbsoluteFill
+ style={{
+ alignItems: 'center',
+ backgroundColor: '#111827',
+ flexDirection: 'row',
+ gap: 14,
+ justifyContent: 'center',
+ }}
+ >
+ <Tile label="1x" pixelDensity={1} />
+ <Tile label="2x" pixelDensity={2} />
+ <Tile label="10x" pixelDensity={10} />
+ </AbsoluteFill>
+ );
+};
diff --git a/packages/example/src/Root.tsx b/packages/example/src/Root.tsx
index 4e9ebfe146..646863c0bb 100644
--- a/packages/example/src/Root.tsx
+++ b/packages/example/src/Root.tsx
@@ -68,6 +68,7 @@ import {
HtmlInCanvasDocsDemo2DBlur,
HtmlInCanvasDocsMinimalWebGL,
HtmlInCanvasDocsMinimalWebGPU,
+ HtmlInCanvasPixelDensity,
HtmlInCanvasPrivacy,
HtmlInCanvasReactSvg,
LinearBlurTransitionDoc,
@@ -1003,6 +1004,14 @@ export const Index: React.FC = () => {
width={1920}
durationInFrames={120}
/>
+ <Composition
+ id="html-in-canvas-pixel-density"
+ component={HtmlInCanvasPixelDensity}
+ fps={30}
+ height={80}
+ width={250}
+ durationInFrames={60}
+ />
<Composition
id="html-in-canvas-compose-async-bitmap"
component={HtmlInCanvasComposeAsyncBitmap}
@@ -2097,8 +2106,8 @@ export const Index: React.FC = () => {
durationInFrames={120}
/>
{/**
- *
- *
+ *
+ *
* disabled for react 19
<Folder name="Skia">
<Composition