Skip to content

🎥 Make videos programmatically with React

Add CanvasImage component

Cursor Agent17429f78118b
diff --git a/packages/core/src/animated-image/canvas.tsx b/packages/core/src/animated-image/canvas.tsx
index 2895e9d16d..fa57d6e35f 100644
--- a/packages/core/src/animated-image/canvas.tsx
+++ b/packages/core/src/animated-image/canvas.tsx
@@ -1,80 +1,10 @@
import React, {useCallback, useImperativeHandle, useMemo, useRef} from 'react';
+import {calculateImageFit} from '../calculate-image-fit.js';
import type {EffectDefinitionAndStack} from '../effects/effect-types.js';
import {runEffectChain} from '../effects/run-effect-chain.js';
import {useEffectChainState} from '../effects/use-effect-chain-state.js';
import type {AnimatedImageFillMode} from './props';
-const calcArgs = (
- fit: AnimatedImageFillMode,
- frameSize: {
- width: number;
- height: number;
- },
- canvasSize: {
- width: number;
- height: number;
- },
-): [number, number, number, number, number, number, number, number] => {
- switch (fit) {
- case 'fill': {
- return [
- 0,
- 0,
- frameSize.width,
- frameSize.height,
- 0,
- 0,
- canvasSize.width,
- canvasSize.height,
- ];
- }
-
- case 'contain': {
- const ratio = Math.min(
- canvasSize.width / frameSize.width,
- canvasSize.height / frameSize.height,
- );
-
- const centerX = (canvasSize.width - frameSize.width * ratio) / 2;
- const centerY = (canvasSize.height - frameSize.height * ratio) / 2;
-
- return [
- 0,
- 0,
- frameSize.width,
- frameSize.height,
- centerX,
- centerY,
- frameSize.width * ratio,
- frameSize.height * ratio,
- ];
- }
-
- case 'cover': {
- const ratio = Math.max(
- canvasSize.width / frameSize.width,
- canvasSize.height / frameSize.height,
- );
- const centerX = (canvasSize.width - frameSize.width * ratio) / 2;
- const centerY = (canvasSize.height - frameSize.height * ratio) / 2;
-
- return [
- 0,
- 0,
- frameSize.width,
- frameSize.height,
- centerX,
- centerY,
- frameSize.width * ratio,
- frameSize.height * ratio,
- ];
- }
-
- default:
- throw new Error('Unknown fit: ' + fit);
- }
-};
-
type Props = {
readonly width?: number;
@@ -132,7 +62,7 @@ const CanvasRefForwardingFunction: React.ForwardRefRenderFunction<
sourceCtx.drawImage(
imageData,
- ...calcArgs(
+ ...calculateImageFit(
fit,
{
height: imageData.displayHeight,
diff --git a/packages/core/src/animated-image/props.ts b/packages/core/src/animated-image/props.ts
index 79d8b72ba7..9f56c46c0b 100644
--- a/packages/core/src/animated-image/props.ts
+++ b/packages/core/src/animated-image/props.ts
@@ -1,3 +1,4 @@
+import type {ImageFit} from '../calculate-image-fit.js';
import type {EffectsProp} from '../effects/effect-types.js';
import type {SequenceProps} from '../Sequence.js';
@@ -28,4 +29,4 @@ export type AnimatedImageProps = Omit<
readonly effects?: EffectsProp;
};
-export type AnimatedImageFillMode = 'contain' | 'cover' | 'fill';
+export type AnimatedImageFillMode = ImageFit;
diff --git a/packages/core/src/calculate-image-fit.ts b/packages/core/src/calculate-image-fit.ts
new file mode 100644
index 0000000000..601a537d63
--- /dev/null
+++ b/packages/core/src/calculate-image-fit.ts
@@ -0,0 +1,72 @@
+export type ImageFit = 'contain' | 'cover' | 'fill';
+
+export const calculateImageFit = (
+ fit: ImageFit,
+ imageSize: {
+ width: number;
+ height: number;
+ },
+ canvasSize: {
+ width: number;
+ height: number;
+ },
+): [number, number, number, number, number, number, number, number] => {
+ switch (fit) {
+ case 'fill': {
+ return [
+ 0,
+ 0,
+ imageSize.width,
+ imageSize.height,
+ 0,
+ 0,
+ canvasSize.width,
+ canvasSize.height,
+ ];
+ }
+
+ case 'contain': {
+ const ratio = Math.min(
+ canvasSize.width / imageSize.width,
+ canvasSize.height / imageSize.height,
+ );
+
+ const centerX = (canvasSize.width - imageSize.width * ratio) / 2;
+ const centerY = (canvasSize.height - imageSize.height * ratio) / 2;
+
+ return [
+ 0,
+ 0,
+ imageSize.width,
+ imageSize.height,
+ centerX,
+ centerY,
+ imageSize.width * ratio,
+ imageSize.height * ratio,
+ ];
+ }
+
+ case 'cover': {
+ const ratio = Math.max(
+ canvasSize.width / imageSize.width,
+ canvasSize.height / imageSize.height,
+ );
+ const centerX = (canvasSize.width - imageSize.width * ratio) / 2;
+ const centerY = (canvasSize.height - imageSize.height * ratio) / 2;
+
+ return [
+ 0,
+ 0,
+ imageSize.width,
+ imageSize.height,
+ centerX,
+ centerY,
+ imageSize.width * ratio,
+ imageSize.height * ratio,
+ ];
+ }
+
+ default:
+ throw new Error('Unknown fit: ' + fit);
+ }
+};
diff --git a/packages/core/src/canvas-image/CanvasImage.tsx b/packages/core/src/canvas-image/CanvasImage.tsx
new file mode 100644
index 0000000000..9a155e76e4
--- /dev/null
+++ b/packages/core/src/canvas-image/CanvasImage.tsx
@@ -0,0 +1,399 @@
+import React, {
+ forwardRef,
+ useCallback,
+ useEffect,
+ useMemo,
+ useState,
+} from 'react';
+import {calculateImageFit} from '../calculate-image-fit.js';
+import type {SequenceControls} from '../CompositionManager.js';
+import type {EffectsProp} from '../effects/effect-types.js';
+import {runEffectChain} from '../effects/run-effect-chain.js';
+import {useEffectChainState} from '../effects/use-effect-chain-state.js';
+import {
+ useMemoizedEffectDefinitions,
+ useMemoizedEffects,
+} from '../effects/use-memoized-effects.js';
+import {addSequenceStackTraces} from '../enable-sequence-stack-traces.js';
+import {truncateSrcForLabel} from '../Img.js';
+import {usePreload} from '../prefetch.js';
+import {
+ hiddenField,
+ sequenceVisualStyleSchema,
+ type SequenceSchema,
+} from '../sequence-field-schema.js';
+import {Sequence} from '../Sequence.js';
+import {useDelayRender} from '../use-delay-render.js';
+import {wrapInSchema} from '../wrap-in-schema.js';
+import type {CanvasImageProps} from './props.js';
+
+const canvasImageSchema = {
+ width: {
+ type: 'number',
+ min: 1,
+ step: 1,
+ default: undefined,
+ description: 'Width',
+ },
+ height: {
+ type: 'number',
+ min: 1,
+ step: 1,
+ default: undefined,
+ description: 'Height',
+ },
+ fit: {
+ type: 'enum',
+ default: 'fill',
+ description: 'Fit',
+ variants: {
+ fill: {},
+ contain: {},
+ cover: {},
+ },
+ },
+ ...sequenceVisualStyleSchema,
+ hidden: hiddenField,
+} as const satisfies SequenceSchema;
+
+type LoadedImage = {
+ readonly element: HTMLImageElement;
+ readonly width: number;
+ readonly height: number;
+};
+
+const makeAbortError = () => {
+ if (typeof DOMException !== 'undefined') {
+ return new DOMException('Image loading was aborted', 'AbortError');
+ }
+
+ const error = new Error('Image loading was aborted');
+ error.name = 'AbortError';
+ return error;
+};
+
+const loadImage = ({
+ src,
+ signal,
+}: {
+ readonly src: string;
+ readonly signal: AbortSignal;
+}): Promise<LoadedImage> => {
+ return new Promise((resolve, reject) => {
+ const image = new Image();
+ let settled = false;
+
+ const cleanup = () => {
+ image.onload = null;
+ image.onerror = null;
+ signal.removeEventListener('abort', onAbort);
+ };
+
+ const settle = (callback: () => void) => {
+ if (settled) {
+ return;
+ }
+
+ settled = true;
+ cleanup();
+ callback();
+ };
+
+ const onAbort = () => {
+ settle(() => reject(makeAbortError()));
+ };
+
+ image.onload = () => {
+ Promise.resolve(image.decode?.())
+ .catch(() => undefined)
+ .then(() => {
+ const imageWidth = image.naturalWidth || image.width;
+ const imageHeight = image.naturalHeight || image.height;
+ if (imageWidth <= 0 || imageHeight <= 0) {
+ settle(() =>
+ reject(
+ new Error(
+ `Could not determine dimensions for <CanvasImage> with src="${truncateSrcForLabel(
+ src,
+ )}"`,
+ ),
+ ),
+ );
+ return;
+ }
+
+ settle(() =>
+ resolve({element: image, width: imageWidth, height: imageHeight}),
+ );
+ });
+ };
+
+ image.onerror = () => {
+ settle(() =>
+ reject(
+ new Error(
+ `Could not load <CanvasImage> with src="${truncateSrcForLabel(src)}"`,
+ ),
+ ),
+ );
+ };
+
+ signal.addEventListener('abort', onAbort, {once: true});
+ if (signal.aborted) {
+ onAbort();
+ return;
+ }
+
+ image.crossOrigin = 'anonymous';
+ image.src = src;
+ });
+};
+
+type CanvasImageContentProps = Pick<
+ CanvasImageProps,
+ 'className' | 'fit' | 'height' | 'id' | 'onError' | 'src' | 'style' | 'width'
+> & {
+ readonly effects: EffectsProp;
+ readonly controls: SequenceControls | undefined;
+};
+
+const CanvasImageContent = forwardRef<
+ HTMLCanvasElement,
+ CanvasImageContentProps
+>(
+ (
+ {
+ src,
+ width,
+ height,
+ fit = 'fill',
+ effects,
+ controls,
+ onError,
+ className,
+ style,
+ id,
+ },
+ ref,
+ ) => {
+ const {delayRender, continueRender, cancelRender} = useDelayRender();
+ const [outputCanvas, setOutputCanvas] = useState<HTMLCanvasElement | null>(
+ null,
+ );
+ const actualSrc = usePreload(src);
+ const chainState = useEffectChainState();
+ const memoizedEffects = useMemoizedEffects({
+ effects,
+ overrideId: controls?.overrideId ?? null,
+ });
+
+ const sourceCanvas = useMemo(() => {
+ if (typeof document === 'undefined') {
+ return null;
+ }
+
+ return document.createElement('canvas');
+ }, []);
+
+ const canvasRef = useCallback(
+ (canvas: HTMLCanvasElement | null) => {
+ setOutputCanvas(canvas);
+
+ if (typeof ref === 'function') {
+ ref(canvas);
+ } else if (ref) {
+ ref.current = canvas;
+ }
+ },
+ [ref],
+ );
+
+ useEffect(() => {
+ if (!outputCanvas || !sourceCanvas) {
+ return;
+ }
+
+ const handle = delayRender(
+ `Rendering <CanvasImage> with src="${truncateSrcForLabel(actualSrc)}"`,
+ );
+ const controller = new AbortController();
+ let cancelled = false;
+ let continued = false;
+ const continueRenderOnce = () => {
+ if (continued) {
+ return;
+ }
+
+ continued = true;
+ continueRender(handle);
+ };
+
+ loadImage({src: actualSrc, signal: controller.signal})
+ .then(async (image) => {
+ if (cancelled) {
+ return;
+ }
+
+ const canvasWidth = width ?? image.width;
+ const canvasHeight = height ?? image.height;
+ const sourceContext = sourceCanvas.getContext('2d', {
+ colorSpace: 'srgb',
+ });
+
+ if (!sourceContext) {
+ throw new Error(
+ 'Could not get 2D context for <CanvasImage> source canvas',
+ );
+ }
+
+ sourceCanvas.width = canvasWidth;
+ sourceCanvas.height = canvasHeight;
+ outputCanvas.width = canvasWidth;
+ outputCanvas.height = canvasHeight;
+
+ sourceContext.clearRect(0, 0, canvasWidth, canvasHeight);
+ sourceContext.drawImage(
+ image.element,
+ ...calculateImageFit(
+ fit,
+ {width: image.width, height: image.height},
+ {width: canvasWidth, height: canvasHeight},
+ ),
+ );
+
+ return runEffectChain({
+ state: chainState.get(canvasWidth, canvasHeight)!,
+ source: sourceCanvas,
+ effects: memoizedEffects,
+ output: outputCanvas,
+ width: canvasWidth,
+ height: canvasHeight,
+ });
+ })
+ .then((completed) => {
+ if (completed && !cancelled) {
+ continueRenderOnce();
+ }
+ })
+ .catch((err) => {
+ if ((err as Error).name === 'AbortError') {
+ continueRenderOnce();
+ return;
+ }
+
+ if (onError) {
+ onError(err as Error);
+ continueRenderOnce();
+ } else {
+ cancelRender(err);
+ }
+ });
+
+ return () => {
+ cancelled = true;
+ controller.abort();
+ continueRenderOnce();
+ };
+ }, [
+ actualSrc,
+ cancelRender,
+ chainState,
+ continueRender,
+ delayRender,
+ fit,
+ height,
+ memoizedEffects,
+ onError,
+ outputCanvas,
+ sourceCanvas,
+ width,
+ ]);
+
+ return (
+ <canvas
+ ref={canvasRef}
+ width={width}
+ height={height}
+ className={className}
+ style={style}
+ id={id}
+ />
+ );
+ },
+);
+
+CanvasImageContent.displayName = 'CanvasImageContent';
+
+const CanvasImageInner = forwardRef<
+ HTMLCanvasElement,
+ CanvasImageProps & {
+ readonly _experimentalControls?: SequenceControls | undefined;
+ }
+>(
+ (
+ {
+ src,
+ width,
+ height,
+ fit,
+ effects = [],
+ className,
+ style,
+ id,
+ onError,
+ durationInFrames,
+ from,
+ hidden,
+ name,
+ showInTimeline,
+ stack,
+ _experimentalControls: controls,
+ },
+ ref,
+ ) => {
+ if (!src) {
+ throw new Error('No "src" prop was passed to <CanvasImage>.');
+ }
+
+ const memoizedEffectDefinitions = useMemoizedEffectDefinitions(effects);
+
+ return (
+ <Sequence
+ layout="none"
+ from={from ?? 0}
+ durationInFrames={durationInFrames ?? Infinity}
+ hidden={hidden}
+ showInTimeline={showInTimeline ?? true}
+ name={name ?? '<CanvasImage>'}
+ _experimentalControls={controls}
+ _remotionInternalEffects={memoizedEffectDefinitions}
+ _remotionInternalIsMedia={{type: 'image', src}}
+ _remotionInternalStack={stack}
+ >
+ <CanvasImageContent
+ ref={ref}
+ src={src}
+ width={width}
+ height={height}
+ fit={fit}
+ effects={effects}
+ controls={controls}
+ className={className}
+ style={style}
+ id={id}
+ onError={onError}
+ />
+ </Sequence>
+ );
+ },
+);
+
+/*
+ * @description Renders a static image to a `<canvas>` and applies Remotion effects.
+ * @see [Documentation](https://www.remotion.dev/docs/canvasimage)
+ */
+export const CanvasImage = wrapInSchema(CanvasImageInner, canvasImageSchema);
+
+CanvasImage.displayName = 'CanvasImage';
+
+addSequenceStackTraces(CanvasImage);
diff --git a/packages/core/src/canvas-image/index.ts b/packages/core/src/canvas-image/index.ts
new file mode 100644
index 0000000000..07e99f4123
--- /dev/null
+++ b/packages/core/src/canvas-image/index.ts
@@ -0,0 +1,2 @@
+export {CanvasImage} from './CanvasImage.js';
+export type {CanvasImageProps} from './props.js';
diff --git a/packages/core/src/canvas-image/props.ts b/packages/core/src/canvas-image/props.ts
new file mode 100644
index 0000000000..77564a8b06
--- /dev/null
+++ b/packages/core/src/canvas-image/props.ts
@@ -0,0 +1,26 @@
+import type React from 'react';
+import type {ImageFit} from '../calculate-image-fit.js';
+import type {EffectsProp} from '../effects/effect-types.js';
+import type {SequenceProps} from '../Sequence.js';
+
+type CanvasImageSequenceProps = Pick<
+ SequenceProps,
+ 'durationInFrames' | 'from' | 'hidden' | 'name' | 'showInTimeline'
+> & {
+ /**
+ * @deprecated For internal use only.
+ */
+ readonly stack?: string;
+};
+
+export type CanvasImageProps = CanvasImageSequenceProps & {
+ readonly src: string;
+ readonly width?: number;
+ readonly height?: number;
+ readonly fit?: ImageFit;
+ readonly effects?: EffectsProp;
+ readonly className?: string;
+ readonly style?: React.CSSProperties;
+ readonly id?: string;
+ readonly onError?: (error: Error) => void;
+};
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index c526aee732..498b5f2dfd 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -160,6 +160,12 @@ export {Artifact} from './Artifact.js';
export {Audio, Html5Audio, RemotionAudioProps} from './audio/index.js';
export type {LoopVolumeCurveBehavior} from './audio/use-audio-frame.js';
export {cancelRender} from './cancel-render.js';
+/**
+ * @description Renders a static image to a `<canvas>` and applies Remotion effects.
+ * @see [Documentation](https://www.remotion.dev/docs/canvasimage)
+ */
+export {CanvasImage} from './canvas-image/index.js';
+export type {CanvasImageProps} from './canvas-image/index.js';
export type {Codec} from './codec.js';
export {
CalculateMetadataFunction,
diff --git a/packages/core/src/test/canvas-image.test.tsx b/packages/core/src/test/canvas-image.test.tsx
new file mode 100644
index 0000000000..4e91ff829e
--- /dev/null
+++ b/packages/core/src/test/canvas-image.test.tsx
@@ -0,0 +1,183 @@
+import {afterEach, beforeEach, expect, test} from 'bun:test';
+import {cleanup, render, waitFor} from '@testing-library/react';
+import React from 'react';
+import {CanvasImage} from '../canvas-image/index.js';
+import type {
+ EffectApplyParams,
+ EffectDefinition,
+ EffectDescriptor,
+} from '../effects/effect-types.js';
+import {WrapSequenceContext} from './wrap-sequence-context.js';
+
+type DrawImageCall = {
+ readonly canvas: HTMLCanvasElement;
+ readonly args: unknown[];
+};
+
+const drawImageCalls: DrawImageCall[] = [];
+
+const stub2dContext = (canvas: HTMLCanvasElement) => ({
+ canvas,
+ fillStyle: '',
+ fillRect: () => undefined,
+ clearRect: () => undefined,
+ drawImage: (...args: unknown[]) => {
+ drawImageCalls.push({canvas, args});
+ },
+ reset: () => undefined,
+ getImageData: () => ({
+ data: new Uint8ClampedArray(4),
+ width: 1,
+ height: 1,
+ }),
+ putImageData: () => undefined,
+});
+
+(
+ HTMLCanvasElement.prototype as unknown as {
+ getContext: (kind: string) => unknown;
+ }
+).getContext = function (kind: string) {
+ if (kind === '2d') {
+ return stub2dContext(this as HTMLCanvasElement);
+ }
+
+ return null;
+};
+
+class MockImage {
+ public onload: (() => void) | null = null;
+ public onerror: (() => void) | null = null;
+ public crossOrigin: string | null = null;
+ public naturalWidth = 200;
+ public naturalHeight = 100;
+ public width = 200;
+ public height = 100;
+ public decode = () => Promise.resolve();
+ private currentSrc = '';
+
+ public set src(src: string) {
+ this.currentSrc = src;
+ queueMicrotask(() => this.onload?.());
+ }
+
+ public get src() {
+ return this.currentSrc;
+ }
+}
+
+const OriginalImage = globalThis.Image;
+
+beforeEach(() => {
+ drawImageCalls.length = 0;
+ globalThis.Image = MockImage as unknown as typeof Image;
+});
+
+afterEach(() => {
+ cleanup();
+ globalThis.Image = OriginalImage;
+});
+
+test('<CanvasImage> renders a canvas element with the decoded image dimensions', async () => {
+ const {container} = render(
+ <WrapSequenceContext>
+ <CanvasImage src="test.png" />
+ </WrapSequenceContext>,
+ );
+
+ const canvas = container.querySelector('canvas');
+ expect(canvas?.tagName).toBe('CANVAS');
+
+ await waitFor(() => {
+ expect(canvas?.getAttribute('width')).toBe('200');
+ expect(canvas?.getAttribute('height')).toBe('100');
+ });
+});
+
+test('<CanvasImage> forwards a canvas ref', async () => {
+ const ref = React.createRef<HTMLCanvasElement>();
+
+ render(
+ <WrapSequenceContext>
+ <CanvasImage ref={ref} src="test.png" width={120} height={80} />
+ </WrapSequenceContext>,
+ );
+
+ await waitFor(() => {
+ expect(ref.current?.tagName).toBe('CANVAS');
+ expect(ref.current?.getAttribute('width')).toBe('120');
+ expect(ref.current?.getAttribute('height')).toBe('80');
+ });
+});
+
+test('<CanvasImage> applies contain fit when drawing into the source canvas', async () => {
+ render(
+ <WrapSequenceContext>
+ <CanvasImage src="test.png" width={100} height={100} fit="contain" />
+ </WrapSequenceContext>,
+ );
+
+ await waitFor(() => {
+ expect(drawImageCalls.length).toBeGreaterThanOrEqual(1);
+ });
+
+ expect(drawImageCalls[0].args.slice(1)).toEqual([
+ 0, 0, 200, 100, 0, 25, 100, 50,
+ ]);
+});
+
+test('<CanvasImage> applies cover fit when drawing into the source canvas', async () => {
+ render(
+ <WrapSequenceContext>
+ <CanvasImage src="test.png" width={100} height={100} fit="cover" />
+ </WrapSequenceContext>,
+ );
+
+ await waitFor(() => {
+ expect(drawImageCalls.length).toBeGreaterThanOrEqual(1);
+ });
+
+ expect(drawImageCalls[0].args.slice(1)).toEqual([
+ 0, 0, 200, 100, -50, 0, 200, 100,
+ ]);
+});
+
+test('<CanvasImage> runs static images through an effect chain', async () => {
+ const applyCalls: EffectApplyParams<unknown, unknown>[] = [];
+ const definition: EffectDefinition<unknown> = {
+ type: 'test-effect',
+ label: 'Test effect',
+ backend: '2d',
+ calculateKey: () => 'test-effect',
+ setup: () => ({}),
+ apply: (params) => {
+ applyCalls.push(params);
+ params.target
+ .getContext('2d')
+ ?.drawImage(params.source, 0, 0, params.width, params.height);
+ },
+ cleanup: () => undefined,
+ schema: {},
+ validateParams: () => undefined,
+ };
+ const effect: EffectDescriptor<unknown> = {
+ definition,
+ effectKey: 'test-effect',
+ params: {},
+ memoized: false,
+ };
+
+ render(
+ <WrapSequenceContext>
+ <CanvasImage src="test.png" width={100} height={50} effects={[effect]} />
+ </WrapSequenceContext>,
+ );
+
+ await waitFor(() => {
+ expect(applyCalls).toHaveLength(1);
+ });
+
+ expect(applyCalls[0].width).toBe(100);
+ expect(applyCalls[0].height).toBe(50);
+ expect(applyCalls[0].source).toBeInstanceOf(HTMLCanvasElement);
+});
diff --git a/packages/docs/docs/canvasimage.mdx b/packages/docs/docs/canvasimage.mdx
new file mode 100644
index 0000000000..2cde54645f
--- /dev/null
+++ b/packages/docs/docs/canvasimage.mdx
@@ -0,0 +1,102 @@
+---
+image: /generated/articles-docs-canvasimage.png
+id: canvasimage
+title: '<CanvasImage>'
+crumb: 'API'
+---
+
+# &lt;CanvasImage&gt;<AvailableFrom v="4.0.466" />
+
+Renders a static image onto a [`<canvas>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/canvas) element.
+
+Use it when you want to apply Remotion [`effects`](/docs/effects) to a static image.
+Use [`<Img>`](/docs/img) if you need a regular `<img>` tag without effects.
+
+```tsx twoslash title="MyComp.tsx"
+import {AbsoluteFill, CanvasImage, staticFile} from 'remotion';
+
+export const MyComp: React.FC = () => {
+ return (
+ <AbsoluteFill>
+ <CanvasImage src={staticFile('image.png')} width={1920} height={1080} />
+ </AbsoluteFill>
+ );
+};
+```
+
+## API
+
+### `src`
+
+The URL of the image. Can be a remote URL or a local file path from [`staticFile()`](/docs/staticfile).
+
+Remote images need to support [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) because the image is drawn onto a canvas.
+
+### `width?`
+
+The canvas width in pixels.
+If omitted, the decoded image width is used.
+
+### `height?`
+
+The canvas height in pixels.
+If omitted, the decoded image height is used.
+
+### `fit?`
+
+Must be one of these values:
+
+- `'fill'`: The image will completely fill the canvas, and will be stretched if necessary. (_default_)
+- `'contain'`: The image is scaled to fit the canvas, while aspect ratio is maintained.
+- `'cover'`: The image completely fills the canvas and maintains its aspect ratio. It will be cropped if necessary.
+
+### `effects?`
+
+An array of Remotion effects to apply to the image after it has been drawn to the source canvas.
+
+### `className?`
+
+A class name to apply to the `<canvas>` element.
+
+### `style?`
+
+Inline styles to apply to the `<canvas>` element.
+
+### `id?`
+
+An ID to apply to the `<canvas>` element.
+
+### `onError?`
+
+Called when the image cannot be loaded, decoded, or drawn.
+If omitted, [`cancelRender()`](/docs/cancel-render) is called.
+
+### Inherited props
+
+`<CanvasImage>` inherits [`from`](/docs/sequence#from), [`durationInFrames`](/docs/sequence#durationinframes), [`name`](/docs/sequence#name), [`showInTimeline`](/docs/sequence#showintimeline) and [`hidden`](/docs/sequence#hidden) from [`<Sequence>`](/docs/sequence).
+
+## Adding a ref
+
+You can add a [React ref](https://react.dev/learn/manipulating-the-dom-with-refs) to a `<CanvasImage>` component.
+If you use TypeScript, type it with `HTMLCanvasElement`:
+
+```tsx twoslash title="MyComp.tsx"
+import {useRef} from 'react';
+import {CanvasImage, staticFile} from 'remotion';
+
+export const MyComp: React.FC = () => {
+ const ref = useRef<HTMLCanvasElement>(null);
+
+ return <CanvasImage ref={ref} src={staticFile('image.png')} />;
+};
+```
+
+## Compatibility
+
+<CompatibilityTable chrome firefox safari nodejs="" bun="" serverlessFunctions="" clientSideRendering serverSideRendering player studio hideServers />
+
+## See also
+
+- [Source code for this component](https://github.com/remotion-dev/remotion/blob/main/packages/core/src/canvas-image/CanvasImage.tsx)
+- [`<Img>`](/docs/img)
+- [`<AnimatedImage>`](/docs/animatedimage)
diff --git a/packages/docs/docs/remotion/table-of-contents.tsx b/packages/docs/docs/remotion/table-of-contents.tsx
index 2adeb41595..f0b79e9bdb 100644
--- a/packages/docs/docs/remotion/table-of-contents.tsx
+++ b/packages/docs/docs/remotion/table-of-contents.tsx
@@ -76,6 +76,10 @@ export const TableOfContents: React.FC = () => {
Render an <code>{'<img>'}</code> tag and wait for it to load
</div>
</TOCItem>
+ <TOCItem link="/docs/canvasimage">
+ <strong>{'<CanvasImage>'}</strong>
+ <div>Render an image into a canvas and apply effects</div>
+ </TOCItem>
<TOCItem link="/docs/interpolate-colors">
<strong>interpolateColors()</strong>
<div>Map a range of values to colors</div>
diff --git a/packages/docs/sidebars.ts b/packages/docs/sidebars.ts
index 0e99141644..96f8077ff9 100644
--- a/packages/docs/sidebars.ts
+++ b/packages/docs/sidebars.ts
@@ -158,6 +158,7 @@ const sidebars: SidebarsConfig = {
'remotion/html-in-canvas',
'iframe',
'img',
+ 'canvasimage',
'interpolate-colors',
'interpolate',
'loop',
diff --git a/packages/docs/src/data/articles.ts b/packages/docs/src/data/articles.ts
index 1dc61c4bb4..81c3757898 100644
--- a/packages/docs/src/data/articles.ts
+++ b/packages/docs/src/data/articles.ts
@@ -521,6 +521,15 @@ export const articles = [
noAi: false,
slug: 'cancel-render',
},
+ {
+ id: 'canvasimage',
+ title: '<CanvasImage>',
+ relativePath: 'docs/canvasimage.mdx',
+ compId: 'articles-docs-canvasimage',
+ crumb: 'API',
+ noAi: false,
+ slug: 'canvasimage',
+ },
{
id: 'captions/api',
title: '@remotion/captions',
diff --git a/packages/docs/static/generated/articles-docs-canvasimage.png b/packages/docs/static/generated/articles-docs-canvasimage.png
new file mode 100644
index 0000000000..3d5c2109f9
Binary files /dev/null and b/packages/docs/static/generated/articles-docs-canvasimage.png differ