Skip to content

🎥 Make videos programmatically with React

remotion: Add Img effects fallback

JonnyBurger79794d25bee0
diff --git a/packages/core/src/Img.tsx b/packages/core/src/Img.tsx
index 2f9f376333..f55945f965 100644
--- a/packages/core/src/Img.tsx
+++ b/packages/core/src/Img.tsx
@@ -6,7 +6,10 @@ import React, {
useRef,
} from 'react';
import type {IsExact} from './audio/props.js';
+import {CanvasImage} from './canvas-image/index.js';
+import type {CanvasImageProps} from './canvas-image/props.js';
import type {SequenceControls} from './CompositionManager.js';
+import type {EffectsProp} from './effects/effect-types.js';
import {addSequenceStackTraces} from './enable-sequence-stack-traces.js';
import {getCrossOriginValue} from './get-cross-origin-value.js';
import {usePreload} from './prefetch.js';
@@ -17,6 +20,7 @@ import {
import type {SequenceProps} from './Sequence.js';
import {Sequence} from './Sequence.js';
import {SequenceContext} from './SequenceContext.js';
+import {truncateSrcForLabel} from './truncate-src-for-label.js';
import {useBufferState} from './use-buffer-state.js';
import {useDelayRender} from './use-delay-render.js';
import {useRemotionEnvironment} from './use-remotion-environment.js';
@@ -26,15 +30,7 @@ function exponentialBackoff(errorCount: number): number {
return 1000 * 2 ** (errorCount - 1);
}
-// Data URLs like the ones from canvas.toDataURL() can be many megabytes, which makes the delayRender() label
-// unreadable and bloats log output
-export function truncateSrcForLabel(src: string): string {
- if (src.startsWith('data:') && src.length > 100) {
- return src.slice(0, 60) + '...[' + src.length + ' chars total]';
- }
-
- return src;
-}
+export {truncateSrcForLabel};
type NativeImgProps = Omit<
React.DetailedHTMLProps<
@@ -51,6 +47,7 @@ export type ImgProps = NativeImgProps & {
readonly delayRenderTimeoutInMilliseconds?: number;
readonly onImageFrame?: (imageElement: HTMLImageElement) => void;
readonly src: string;
+ readonly effects?: EffectsProp;
readonly showInTimeline?: boolean;
readonly name?: string;
/**
@@ -66,7 +63,13 @@ type Expected = Omit<
type ImgContentProps = Omit<
ImgProps,
- 'hidden' | 'name' | 'stack' | 'showInTimeline' | 'from' | 'durationInFrames'
+ | 'hidden'
+ | 'name'
+ | 'stack'
+ | 'showInTimeline'
+ | 'from'
+ | 'durationInFrames'
+ | 'effects'
>;
const ImgContent: React.FC<ImgContentProps> = ({
@@ -296,11 +299,11 @@ const ImgContent: React.FC<ImgContentProps> = ({
);
};
-const ImgInner: React.FC<
- ImgProps & {
- readonly _experimentalControls: SequenceControls | undefined;
- }
-> = ({
+type NativeImgInnerProps = Omit<ImgProps, 'effects'> & {
+ readonly _experimentalControls: SequenceControls | undefined;
+};
+
+const NativeImgInner: React.FC<NativeImgInnerProps> = ({
hidden,
name,
stack,
@@ -335,6 +338,145 @@ const ImgInner: React.FC<
);
};
+const CanvasImageWithPrivateProps = CanvasImage as React.ComponentType<
+ CanvasImageProps & {
+ readonly _experimentalControls?: SequenceControls | undefined;
+ }
+>;
+
+const getPassedPropNames = (props: Record<string, unknown>) => {
+ return Object.keys(props).filter((key) => props[key] !== undefined);
+};
+
+const formatPropList = (props: string[]) => {
+ return props.map((prop) => `"${prop}"`).join(', ');
+};
+
+const validateCanvasImageFallbackProps = ({
+ props,
+ ref,
+ width,
+ height,
+}: {
+ readonly props: Record<string, unknown>;
+ readonly ref: React.Ref<HTMLImageElement> | undefined;
+ readonly width: ImgProps['width'];
+ readonly height: ImgProps['height'];
+}) => {
+ if (typeof width === 'string' || typeof height === 'string') {
+ throw new Error(
+ 'The "width" and "height" props must be numbers on <Img> when effects are passed, because <Img> renders a <CanvasImage>. Use numeric props or CSS dimensions in "style".',
+ );
+ }
+
+ const conflictingProps = getPassedPropNames(props);
+ if (ref !== null && ref !== undefined) {
+ conflictingProps.unshift('ref');
+ }
+
+ if (conflictingProps.length === 0) {
+ return;
+ }
+
+ throw new Error(
+ `The ${formatPropList(conflictingProps)} prop${
+ conflictingProps.length === 1 ? '' : 's'
+ } cannot be used on <Img> when effects are passed, because <Img> renders a <CanvasImage> instead of a native <img>. Remove ${
+ conflictingProps.length === 1 ? 'this prop' : 'these props'
+ } or use <CanvasImage> directly.`,
+ );
+};
+
+const ImgInner: React.FC<
+ ImgProps & {
+ readonly _experimentalControls: SequenceControls | undefined;
+ }
+> = ({
+ effects = [],
+ ref,
+ hidden,
+ name,
+ stack,
+ showInTimeline,
+ src,
+ from,
+ durationInFrames,
+ _experimentalControls: controls,
+ width,
+ height,
+ className,
+ style,
+ id,
+ pauseWhenLoading,
+ maxRetries,
+ delayRenderRetries,
+ delayRenderTimeoutInMilliseconds,
+ ...props
+}) => {
+ if (effects.length === 0) {
+ return (
+ <NativeImgInner
+ {...props}
+ ref={ref}
+ hidden={hidden}
+ name={name}
+ stack={stack}
+ showInTimeline={showInTimeline}
+ src={src}
+ from={from}
+ durationInFrames={durationInFrames}
+ _experimentalControls={controls}
+ width={width}
+ height={height}
+ className={className}
+ style={style}
+ id={id}
+ pauseWhenLoading={pauseWhenLoading}
+ maxRetries={maxRetries}
+ delayRenderRetries={delayRenderRetries}
+ delayRenderTimeoutInMilliseconds={delayRenderTimeoutInMilliseconds}
+ />
+ );
+ }
+
+ if (!src) {
+ throw new Error('No "src" prop was passed to <Img>.');
+ }
+
+ validateCanvasImageFallbackProps({
+ props,
+ ref,
+ width,
+ height,
+ });
+
+ const canvasWidth = typeof width === 'number' ? width : undefined;
+ const canvasHeight = typeof height === 'number' ? height : undefined;
+
+ return (
+ <CanvasImageWithPrivateProps
+ src={src}
+ width={canvasWidth}
+ height={canvasHeight}
+ effects={effects}
+ className={className}
+ style={style}
+ id={id}
+ pauseWhenLoading={pauseWhenLoading}
+ maxRetries={maxRetries}
+ delayRenderRetries={delayRenderRetries}
+ delayRenderTimeoutInMilliseconds={delayRenderTimeoutInMilliseconds}
+ from={from}
+ durationInFrames={durationInFrames}
+ hidden={hidden}
+ name={name ?? '<Img>'}
+ showInTimeline={showInTimeline}
+ stack={stack}
+ _experimentalControls={controls ?? undefined}
+ />
+ );
+};
+
const imgSchema = {
...sequenceVisualStyleSchema,
hidden: hiddenField,
diff --git a/packages/core/src/canvas-image/CanvasImage.tsx b/packages/core/src/canvas-image/CanvasImage.tsx
index e21ab316ce..61ed4fc54c 100644
--- a/packages/core/src/canvas-image/CanvasImage.tsx
+++ b/packages/core/src/canvas-image/CanvasImage.tsx
@@ -16,7 +16,6 @@ import {
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,
@@ -25,6 +24,7 @@ import {
} from '../sequence-field-schema.js';
import {Sequence} from '../Sequence.js';
import {SequenceContext} from '../SequenceContext.js';
+import {truncateSrcForLabel} from '../truncate-src-for-label.js';
import {useBufferState} from '../use-buffer-state.js';
import {useDelayRender} from '../use-delay-render.js';
import {wrapInSchema} from '../wrap-in-schema.js';
diff --git a/packages/core/src/test/Img.test.tsx b/packages/core/src/test/Img.test.tsx
index d7c1748231..53687c2f36 100644
--- a/packages/core/src/test/Img.test.tsx
+++ b/packages/core/src/test/Img.test.tsx
@@ -1,13 +1,105 @@
-import {afterEach, expect, test} from 'bun:test';
-import {cleanup, render} from '@testing-library/react';
+import {afterEach, beforeEach, expect, test} from 'bun:test';
+import {cleanup, render, waitFor} from '@testing-library/react';
import React from 'react';
+import type {
+ EffectApplyParams,
+ EffectDefinition,
+ EffectDescriptor,
+} from '../effects/effect-types.js';
import {Img} from '../Img.js';
import type {RemotionEnvironment} from '../remotion-environment-context.js';
import {RemotionEnvironmentContext} from '../remotion-environment-context.js';
import {WrapSequenceContext} from './wrap-sequence-context.js';
+const drawImageCalls: unknown[][] = [];
+const OriginalImage = globalThis.Image;
+
+const stub2dContext = () => ({
+ fillStyle: '',
+ fillRect: () => undefined,
+ clearRect: () => undefined,
+ drawImage: (...args: unknown[]) => {
+ drawImageCalls.push(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();
+ }
+
+ 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 get src() {
+ return this.currentSrc;
+ }
+
+ public set src(src: string) {
+ this.currentSrc = src;
+ queueMicrotask(() => this.onload?.());
+ }
+}
+
+const makeEffect = (
+ applyCalls: EffectApplyParams<unknown, unknown>[] = [],
+): EffectDescriptor<unknown> => {
+ const definition: EffectDefinition<unknown> = {
+ type: 'test-effect',
+ label: 'Test effect',
+ documentationLink: null,
+ 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,
+ };
+
+ return {
+ definition,
+ effectKey: 'test-effect',
+ params: {},
+ memoized: false,
+ };
+};
+
+beforeEach(() => {
+ drawImageCalls.length = 0;
+ globalThis.Image = MockImage as unknown as typeof Image;
+});
+
afterEach(() => {
cleanup();
+ globalThis.Image = OriginalImage;
});
const testImgUrl = 'https://source.unsplash.com/random/50x50';
@@ -24,7 +116,7 @@ const renderImg = (
element: React.ReactElement,
environment: RemotionEnvironment = previewEnvironment,
) => {
- render(
+ return render(
<RemotionEnvironmentContext.Provider value={environment}>
<WrapSequenceContext>{element}</WrapSequenceContext>
</RemotionEnvironmentContext.Provider>,
@@ -68,3 +160,54 @@ test('Img forces synchronous decoding while rendering', () => {
expect(ref.current?.getAttribute('decoding')).toBe('sync');
});
+
+test('Img with an empty effects array still renders an img tag', () => {
+ const ref = React.createRef<HTMLImageElement>();
+ renderImg(<Img ref={ref} src={testImgUrl} effects={[]} />);
+
+ expect(ref.current?.tagName).toBe('IMG');
+});
+
+test('Img with effects renders through the canvas image path', async () => {
+ const applyCalls: EffectApplyParams<unknown, unknown>[] = [];
+ const {container} = renderImg(
+ <Img
+ src={testImgUrl}
+ width={100}
+ height={50}
+ effects={[makeEffect(applyCalls)]}
+ />,
+ );
+
+ const canvas = container.querySelector('canvas');
+ expect(canvas?.tagName).toBe('CANVAS');
+
+ await waitFor(() => {
+ expect(applyCalls).toHaveLength(1);
+ });
+
+ expect(applyCalls[0].width).toBe(100);
+ expect(applyCalls[0].height).toBe(50);
+});
+
+test('Img throws when native image props conflict with effects', () => {
+ expect(() =>
+ renderImg(
+ <Img
+ src={testImgUrl}
+ srcSet={`${testImgUrl} 1x`}
+ effects={[makeEffect()]}
+ />,
+ ),
+ ).toThrow(
+ 'The "srcSet" prop cannot be used on <Img> when effects are passed',
+ );
+});
+
+test('Img throws when a ref is passed together with effects', () => {
+ const ref = React.createRef<HTMLImageElement>();
+
+ expect(() =>
+ renderImg(<Img ref={ref} src={testImgUrl} effects={[makeEffect()]} />),
+ ).toThrow('The "ref" prop cannot be used on <Img> when effects are passed');
+});
diff --git a/packages/core/src/test/truncate-src-for-label.test.ts b/packages/core/src/test/truncate-src-for-label.test.ts
index 5180354cdb..2ae70687b3 100644
--- a/packages/core/src/test/truncate-src-for-label.test.ts
+++ b/packages/core/src/test/truncate-src-for-label.test.ts
@@ -1,5 +1,5 @@
import {expect, test} from 'bun:test';
-import {truncateSrcForLabel} from '../Img.js';
+import {truncateSrcForLabel} from '../truncate-src-for-label.js';
test('leaves http URLs untouched', () => {
const src = 'https://example.com/images/hero.png';
diff --git a/packages/core/src/truncate-src-for-label.ts b/packages/core/src/truncate-src-for-label.ts
new file mode 100644
index 0000000000..0d8adf86d0
--- /dev/null
+++ b/packages/core/src/truncate-src-for-label.ts
@@ -0,0 +1,9 @@
+// Data URLs like the ones from canvas.toDataURL() can be many megabytes, which makes the delayRender() label
+// unreadable and bloats log output
+export function truncateSrcForLabel(src: string): string {
+ if (src.startsWith('data:') && src.length > 100) {
+ return src.slice(0, 60) + '...[' + src.length + ' chars total]';
+ }
+
+ return src;
+}
diff --git a/packages/docs/docs/img.mdx b/packages/docs/docs/img.mdx
index 4558413fef..fa4a40bd34 100644
--- a/packages/docs/docs/img.mdx
+++ b/packages/docs/docs/img.mdx
@@ -41,6 +41,29 @@ export const MyComp: React.FC = () => {
};
```
+### `effects?`<AvailableFrom v="4.0.468" />
+
+Apply [effects](/docs/effects/api) to the image.
+
+When `effects` is omitted or an empty array, `<Img>` renders a native `<img>` element. When at least one effect is passed, `<Img>` renders through [`<CanvasImage>`](/docs/canvasimage).
+
+```tsx twoslash title="MyComp.tsx"
+import {AbsoluteFill, Img, staticFile} from 'remotion';
+import {blur} from '@remotion/effects/blur';
+
+export const MyComp: React.FC = () => {
+ return (
+ <AbsoluteFill>
+ <Img src={staticFile('hi.png')} effects={[blur({radius: 8})]} />
+ </AbsoluteFill>
+ );
+};
+```
+
+Because the element becomes a `<canvas>`, native image props that require an `<img>` element cannot be used with non-empty `effects`.
+
+The unsupported props include `ref`, `srcSet`, `sizes`, `loading`, `decoding`, `fetchPriority`, `useMap`, `crossOrigin`, `onLoad`, `onError`, `onImageFrame` and `alt`.
+
### `onError`
To use the `<Img>` tag in a resilient way, handle the error that occurs when an image can not be loaded:
@@ -106,7 +129,7 @@ export const MyComp: React.FC = () => {
### Other props
-Remotion inherits the props of the regular `<img>` tag, like for example `style`.
+Remotion inherits the props of the regular `<img>` tag, like for example `style`. If [`effects`](#effects) is a non-empty array, only the props supported by [`<CanvasImage>`](/docs/canvasimage) are supported.
## GIFs