Skip to content

πŸŽ₯ Make videos programmatically with React

progress

Igor Samokhovets9a8d3a363851
diff --git a/packages/core/src/Img.tsx b/packages/core/src/Img.tsx
index 28e0fe4219..28cdd5d4a2 100644
--- a/packages/core/src/Img.tsx
+++ b/packages/core/src/Img.tsx
@@ -32,11 +32,20 @@ export type ImgProps = NativeImgProps & {
readonly pauseWhenLoading?: boolean;
readonly delayRenderRetries?: number;
readonly delayRenderTimeoutInMilliseconds?: number;
- readonly onImageFrame?: (imgelement: HTMLImageElement) => void;
+ readonly onImageFrame?: (imageElement: HTMLImageElement) => void;
readonly src: string;
+ /**
+ * @description Controls what happens when the image fails to load or cannot be drawn to canvas (e.g., due to CORS restrictions).
+ * @default 'fail'
+ * @see [Documentation](https://remotion.dev/docs/img)
+ */
+ readonly errorBehavior?: 'fail' | 'ignore';
};
-type Expected = Omit<NativeImgProps, 'onError' | 'src' | 'crossOrigin'>;
+type Expected = Omit<
+ NativeImgProps,
+ 'onError' | 'src' | 'crossOrigin' | 'errorBehavior'
+>;
const ImgRefForwarding: React.ForwardRefRenderFunction<
HTMLImageElement,
@@ -51,6 +60,7 @@ const ImgRefForwarding: React.ForwardRefRenderFunction<
delayRenderTimeoutInMilliseconds,
onImageFrame,
crossOrigin,
+ errorBehavior,
...props
},
ref,
@@ -254,6 +264,9 @@ const ImgRefForwarding: React.ForwardRefRenderFunction<
crossOrigin={crossOriginValue}
onError={didGetError}
decoding="sync"
+ data-remotion-error-behavior={
+ errorBehavior === 'ignore' ? 'ignore' : undefined
+ }
/>
);
};
diff --git a/packages/docs/docs/client-side-rendering/migration.mdx b/packages/docs/docs/client-side-rendering/migration.mdx
index 6dfc1bcaef..0310a992d5 100644
--- a/packages/docs/docs/client-side-rendering/migration.mdx
+++ b/packages/docs/docs/client-side-rendering/migration.mdx
@@ -29,7 +29,45 @@ Start using the [`useDelayRender()`](/docs/use-delay-render) hook instead, which
## Ensure assets are available via CORS
-Unlike server-side rendering, where video and audio assets are downloaded in a Node.js process, and where images can be captured even if they are [tainted](https://www.unblu.com/en/docs/latest/knowledge-base/configuration/collaboration-layers/embedded-co-browsing/html-tainted-canvas-limitation.html), in client-side rendering, CORS is enforced and images and canvas may not be tainted.
+Unlike server-side rendering, where video and audio assets are downloaded in a Node.js process, and where images can be captured even if they are [tainted](https://developer.mozilla.org/en-US/docs/Web/HTML/How_to/CORS_enabled_image#security_and_tainted_canvases), in client-side rendering, CORS is enforced and images and canvas may not be tainted.
+
+### Why CORS is required
+
+Client-side rendering draws images to a `<canvas>` element. For security reasons, browsers restrict access to image data from different origins. If an image from another domain is drawn to a canvas without proper CORS headers, the canvas becomes "tainted" and its contents cannot be extracted.
+
+### Common error messages
+
+If you use an image that doesn't support CORS, you'll see an error like:
+
+```
+Could not draw image with src="https://example.com/image.png" to canvas:
+The image is tainted due to CORS restrictions.
+The server hosting this image must respond with the "Access-Control-Allow-Origin" header.
+```
+
+If an image fails to load entirely (e.g., 404 error, invalid URL), you'll see:
+
+```
+Could not draw image with src="https://example.com/image.png" to canvas:
+The image is in a broken state.
+This usually means the image failed to load - check that the URL is valid and accessible.
+```
+
+### Solutions
+
+1. **Host images with CORS headers**: Ensure your image server responds with `Access-Control-Allow-Origin: *` or a specific origin.
+
+2. **Self-host images**: Download remote images and serve them from your own domain.
+
+3. **Use a CORS proxy**: Route requests through a proxy that adds CORS headers.
+
+4. **Use `errorBehavior="ignore"`**: If you want to gracefully skip images that fail to load or are tainted, use the [`errorBehavior`](/docs/img#errorbehavior) prop on `<Img>`:
+
+```tsx
+<Img src="https://example.com/maybe-cors-enabled.png" errorBehavior="ignore" />
+```
+
+This will render nothing instead of failing the render if the image cannot be drawn to canvas.
## Use `@remotion/media`
diff --git a/packages/docs/docs/img.mdx b/packages/docs/docs/img.mdx
index a1772de52d..503225bb21 100644
--- a/packages/docs/docs/img.mdx
+++ b/packages/docs/docs/img.mdx
@@ -2,7 +2,7 @@
image: /generated/articles-docs-img.png
title: <Img>
id: img
-crumb: "API"
+crumb: 'API'
---
The `<Img>` tag can be used like a regular `<img>` HTML tag.
@@ -16,12 +16,12 @@ If you use `<Img>`, Remotion will ensure that the image is loaded before renderi
[Put an image into the `public/` folder](/docs/assets) and use [`staticFile()`](/docs/staticfile) to reference it.
```tsx twoslash
-import { AbsoluteFill, Img, staticFile } from "remotion";
+import {AbsoluteFill, Img, staticFile} from 'remotion';
export const MyComp: React.FC = () => {
return (
<AbsoluteFill>
- <Img src={staticFile("hi.png")} />
+ <Img src={staticFile('hi.png')} />
</AbsoluteFill>
);
};
@@ -30,12 +30,12 @@ export const MyComp: React.FC = () => {
You can also load a remote image:
```tsx twoslash
-import { AbsoluteFill, Img } from "remotion";
+import {AbsoluteFill, Img} from 'remotion';
export const MyComp: React.FC = () => {
return (
<AbsoluteFill>
- <Img src={"https://picsum.photos/200/300"} />
+ <Img src={'https://picsum.photos/200/300'} />
</AbsoluteFill>
);
};
@@ -46,13 +46,13 @@ export const MyComp: React.FC = () => {
To use the `<Img>` tag in a resilient way, handle the error that occurs when an image can not be loaded:
```tsx twoslash
-import { AbsoluteFill, Img, staticFile } from "remotion";
+import {AbsoluteFill, Img, staticFile} from 'remotion';
export const MyComp: React.FC = () => {
return (
<AbsoluteFill>
<Img
- src={staticFile("hi.png")}
+ src={staticFile('hi.png')}
onError={(event) => {
// Handle image loading error here
}}
@@ -86,6 +86,34 @@ Customize the [timeout](/docs/delay-render#modifying-the-timeout) of the [`delay
Customize the [number of retries](/docs/delay-render#retrying) of the [`delayRender()`](/docs/delay-render) call that this component makes.
Prefer the [`maxRetries`](#maxretries) prop over this.
+### `errorBehavior`<AvailableFrom v="4.0.398" />
+
+_optional_
+
+Controls what happens when the image cannot be drawn to the canvas during [client-side rendering](/docs/client-side-rendering). This can happen when:
+
+- The image fails to load (404, network error, invalid URL)
+- The image is tainted due to CORS restrictions
+
+**Values:**
+
+- `"fail"` (default): The render will fail with an error message explaining the problem.
+- `"ignore"`: The image will be skipped and nothing will be rendered in its place.
+
+```tsx twoslash
+import {AbsoluteFill, Img} from 'remotion';
+
+export const MyComp: React.FC = () => {
+ return (
+ <AbsoluteFill>
+ <Img src="https://example.com/maybe-cors-enabled.png" errorBehavior="ignore" />
+ </AbsoluteFill>
+ );
+};
+```
+
+This prop is primarily useful for client-side rendering where CORS restrictions are enforced. See [Migrating to client-side rendering](/docs/client-side-rendering/migration#ensure-assets-are-available-via-cors) for more information.
+
## Other props
Remotion inherits the props of the regular `<img>` tag, like for example `style`.
diff --git a/packages/web-renderer/src/drawing/draw-dom-element.ts b/packages/web-renderer/src/drawing/draw-dom-element.ts
index 787a48ea6d..0c94f26b55 100644
--- a/packages/web-renderer/src/drawing/draw-dom-element.ts
+++ b/packages/web-renderer/src/drawing/draw-dom-element.ts
@@ -1,6 +1,34 @@
import type {DrawFn} from './drawn-fn';
import {turnSvgIntoDrawable} from './turn-svg-into-drawable';
+const getReadableImageError = (
+ err: unknown,
+ node: HTMLImageElement,
+): Error | null => {
+ if (!(err instanceof DOMException)) {
+ return null;
+ }
+
+ if (err.name === 'SecurityError') {
+ return new Error(
+ `Could not draw image with src="${node.src}" to canvas: ` +
+ `The image is tainted due to CORS restrictions. ` +
+ `The server hosting this image must respond with the "Access-Control-Allow-Origin" header. ` +
+ `See: https://remotion.dev/docs/client-side-rendering/migration`,
+ );
+ }
+
+ if (err.name === 'InvalidStateError') {
+ return new Error(
+ `Could not draw image with src="${node.src}" to canvas: ` +
+ `The image is in a broken state. ` +
+ `This usually means the image failed to load - check that the URL is valid and accessible.`,
+ );
+ }
+
+ return null;
+};
+
export const drawDomElement = (node: HTMLElement | SVGElement) => {
const domDrawFn: DrawFn = async ({dimensions, contextToDraw}) => {
const drawable = await (node instanceof SVGSVGElement
@@ -15,13 +43,33 @@ export const drawDomElement = (node: HTMLElement | SVGElement) => {
return;
}
- contextToDraw.drawImage(
- drawable,
- dimensions.left,
- dimensions.top,
- dimensions.width,
- dimensions.height,
- );
+ try {
+ contextToDraw.drawImage(
+ drawable,
+ dimensions.left,
+ dimensions.top,
+ dimensions.width,
+ dimensions.height,
+ );
+ } catch (err) {
+ // Check if we should ignore errors for this element
+ if (
+ node instanceof HTMLImageElement &&
+ node.dataset.remotionErrorBehavior === 'ignore'
+ ) {
+ return;
+ }
+
+ // Provide readable error messages for image errors
+ if (node instanceof HTMLImageElement) {
+ const readableError = getReadableImageError(err, node);
+ if (readableError) {
+ throw readableError;
+ }
+ }
+
+ throw err;
+ }
};
return domDrawFn;
diff --git a/packages/web-renderer/src/test/__screenshots__/tainted-image.test.tsx/tainted-image-ignored-chromium-darwin.png b/packages/web-renderer/src/test/__screenshots__/tainted-image.test.tsx/tainted-image-ignored-chromium-darwin.png
new file mode 100644
index 0000000000..27c820d7f3
Binary files /dev/null and b/packages/web-renderer/src/test/__screenshots__/tainted-image.test.tsx/tainted-image-ignored-chromium-darwin.png differ
diff --git a/packages/web-renderer/src/test/__screenshots__/tainted-image.test.tsx/tainted-image-ignored-firefox-darwin.png b/packages/web-renderer/src/test/__screenshots__/tainted-image.test.tsx/tainted-image-ignored-firefox-darwin.png
new file mode 100644
index 0000000000..27c820d7f3
Binary files /dev/null and b/packages/web-renderer/src/test/__screenshots__/tainted-image.test.tsx/tainted-image-ignored-firefox-darwin.png differ
diff --git a/packages/web-renderer/src/test/__screenshots__/tainted-image.test.tsx/tainted-image-ignored-webkit-darwin.png b/packages/web-renderer/src/test/__screenshots__/tainted-image.test.tsx/tainted-image-ignored-webkit-darwin.png
new file mode 100644
index 0000000000..27c820d7f3
Binary files /dev/null and b/packages/web-renderer/src/test/__screenshots__/tainted-image.test.tsx/tainted-image-ignored-webkit-darwin.png differ
diff --git a/packages/web-renderer/src/test/tainted-image.test.tsx b/packages/web-renderer/src/test/tainted-image.test.tsx
new file mode 100644
index 0000000000..9dee209c3c
--- /dev/null
+++ b/packages/web-renderer/src/test/tainted-image.test.tsx
@@ -0,0 +1,81 @@
+import {AbsoluteFill, Img} from 'remotion';
+import {expect, test} from 'vitest';
+import {renderStillOnWeb} from '../render-still-on-web';
+import {testImage} from './utils';
+
+// Note: The behavior of tainted images varies by browser:
+// - Chromium/Firefox: Image fails to load when crossOrigin="anonymous" is set
+// and server doesn't support CORS β†’ "broken state" error
+// - WebKit: Image may load as tainted but still render in some cases
+// This test verifies we get a readable error message in either case.
+test('should throw readable error for tainted or broken image', async (t) => {
+ const Component: React.FC = () => {
+ return (
+ <AbsoluteFill>
+ <Img src="https://github.com/JonnyBurger.png" />
+ </AbsoluteFill>
+ );
+ };
+
+ try {
+ await renderStillOnWeb({
+ licenseKey: 'free-license',
+ composition: {
+ component: Component,
+ id: 'tainted-image-test',
+ width: 100,
+ height: 100,
+ fps: 30,
+ durationInFrames: 1,
+ },
+ frame: 0,
+ inputProps: {},
+ imageFormat: 'png',
+ });
+ // WebKit may not throw - that's okay for this test
+ if (t.task.file.projectName === 'webkit') {
+ return;
+ }
+
+ throw new Error('Expected render to fail');
+ } catch (err) {
+ if (!(err instanceof Error)) {
+ throw err;
+ }
+
+ // Should get either a CORS error or a broken state error with a readable message
+ const hasReadableError =
+ err.message.includes('CORS restrictions') ||
+ err.message.includes('broken state') ||
+ err.message.includes('Could not draw image');
+ expect(hasReadableError).toBe(true);
+ }
+});
+
+test('should render nothing when errorBehavior="ignore" for tainted image', async () => {
+ const Component: React.FC = () => {
+ return (
+ <AbsoluteFill style={{backgroundColor: 'red'}}>
+ <Img src="https://github.com/JonnyBurger.png" errorBehavior="ignore" />
+ </AbsoluteFill>
+ );
+ };
+
+ // Should not throw, should render just the red background
+ const {blob} = await renderStillOnWeb({
+ licenseKey: 'free-license',
+ composition: {
+ component: Component,
+ id: 'ignore-error-test',
+ width: 100,
+ height: 100,
+ fps: 30,
+ durationInFrames: 1,
+ },
+ frame: 0,
+ inputProps: {},
+ imageFormat: 'png',
+ });
+
+ await testImage({blob, testId: 'tainted-image-ignored'});
+});