Skip to content

🎥 Make videos programmatically with React

remotion: Address Img effects fallback feedback

JonnyBurger65cdb2d1a1ac
diff --git a/packages/core/src/Img.tsx b/packages/core/src/Img.tsx
index f55945f965..c9c0235ec2 100644
--- a/packages/core/src/Img.tsx
+++ b/packages/core/src/Img.tsx
@@ -6,8 +6,12 @@ import React, {
useRef,
} from 'react';
import type {IsExact} from './audio/props.js';
+import type {ImageFit} from './calculate-image-fit.js';
import {CanvasImage} from './canvas-image/index.js';
-import type {CanvasImageProps} from './canvas-image/props.js';
+import type {
+ CanvasImageCanvasProps,
+ 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';
@@ -16,6 +20,7 @@ import {usePreload} from './prefetch.js';
import {
hiddenField,
sequenceVisualStyleSchema,
+ type SequenceSchema,
} from './sequence-field-schema.js';
import type {SequenceProps} from './Sequence.js';
import {Sequence} from './Sequence.js';
@@ -30,8 +35,6 @@ function exponentialBackoff(errorCount: number): number {
return 1000 * 2 ** (errorCount - 1);
}
-export {truncateSrcForLabel};
-
type NativeImgProps = Omit<
React.DetailedHTMLProps<
React.ImgHTMLAttributes<HTMLImageElement>,
@@ -48,6 +51,7 @@ export type ImgProps = NativeImgProps & {
readonly onImageFrame?: (imageElement: HTMLImageElement) => void;
readonly src: string;
readonly effects?: EffectsProp;
+ readonly fit?: ImageFit;
readonly showInTimeline?: boolean;
readonly name?: string;
/**
@@ -70,6 +74,7 @@ type ImgContentProps = Omit<
| 'from'
| 'durationInFrames'
| 'effects'
+ | 'fit'
>;
const ImgContent: React.FC<ImgContentProps> = ({
@@ -299,7 +304,7 @@ const ImgContent: React.FC<ImgContentProps> = ({
);
};
-type NativeImgInnerProps = Omit<ImgProps, 'effects'> & {
+type NativeImgInnerProps = Omit<ImgProps, 'effects' | 'fit'> & {
readonly _experimentalControls: SequenceControls | undefined;
};
@@ -344,9 +349,25 @@ const CanvasImageWithPrivateProps = CanvasImage as React.ComponentType<
}
>;
-const getPassedPropNames = (props: Record<string, unknown>) => {
- return Object.keys(props).filter((key) => props[key] !== undefined);
-};
+const imgCanvasFallbackIncompatibleProps = new Set([
+ 'alt',
+ 'crossOrigin',
+ 'decoding',
+ 'fetchPriority',
+ 'loading',
+ 'onError',
+ 'onImageFrame',
+ 'onLoad',
+ 'sizes',
+ 'srcSet',
+ 'useMap',
+]);
+
+const getIncompatiblePropNames = (props: Record<string, unknown>) =>
+ Object.keys(props).filter(
+ (key) =>
+ props[key] !== undefined && imgCanvasFallbackIncompatibleProps.has(key),
+ );
const formatPropList = (props: string[]) => {
return props.map((prop) => `"${prop}"`).join(', ');
@@ -369,7 +390,7 @@ const validateCanvasImageFallbackProps = ({
);
}
- const conflictingProps = getPassedPropNames(props);
+ const conflictingProps = getIncompatiblePropNames(props);
if (ref !== null && ref !== undefined) {
conflictingProps.unshift('ref');
}
@@ -381,9 +402,9 @@ const validateCanvasImageFallbackProps = ({
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 ${
+ } cannot be used on <Img> when effects are passed, because <Img> renders a <canvas> instead of a native <img>. Remove ${
conflictingProps.length === 1 ? 'this prop' : 'these props'
- } or use <CanvasImage> directly.`,
+ }.`,
);
};
@@ -404,6 +425,7 @@ const ImgInner: React.FC<
_experimentalControls: controls,
width,
height,
+ fit,
className,
style,
id,
@@ -452,12 +474,14 @@ const ImgInner: React.FC<
const canvasWidth = typeof width === 'number' ? width : undefined;
const canvasHeight = typeof height === 'number' ? height : undefined;
+ const canvasProps = props as CanvasImageCanvasProps;
return (
<CanvasImageWithPrivateProps
src={src}
width={canvasWidth}
height={canvasHeight}
+ fit={fit}
effects={effects}
className={className}
style={style}
@@ -472,15 +496,29 @@ const ImgInner: React.FC<
name={name ?? '<Img>'}
showInTimeline={showInTimeline}
stack={stack}
- _experimentalControls={controls ?? undefined}
+ _remotionInternalDocumentationLink={
+ name === undefined ? 'https://www.remotion.dev/docs/img' : undefined
+ }
+ _experimentalControls={controls}
+ {...canvasProps}
/>
);
};
const imgSchema = {
+ fit: {
+ type: 'enum',
+ default: 'fill',
+ description: 'Fit',
+ variants: {
+ fill: {},
+ contain: {},
+ cover: {},
+ },
+ },
...sequenceVisualStyleSchema,
hidden: hiddenField,
-};
+} as const satisfies SequenceSchema;
/*
* @description Works just like a regular HTML img tag. When you use the <Img> tag, Remotion will ensure that the image is loaded before rendering the frame.
diff --git a/packages/core/src/canvas-image/CanvasImage.tsx b/packages/core/src/canvas-image/CanvasImage.tsx
index 61ed4fc54c..9ee7bedc23 100644
--- a/packages/core/src/canvas-image/CanvasImage.tsx
+++ b/packages/core/src/canvas-image/CanvasImage.tsx
@@ -28,7 +28,7 @@ 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';
-import type {CanvasImageProps} from './props.js';
+import type {CanvasImageCanvasProps, CanvasImageProps} from './props.js';
const canvasImageSchema = {
fit: {
@@ -158,7 +158,7 @@ type CanvasImageContentProps = Pick<
> & {
readonly effects: EffectsProp;
readonly controls: SequenceControls | undefined;
-};
+} & CanvasImageCanvasProps;
const CanvasImageContent = forwardRef<
HTMLCanvasElement,
@@ -180,6 +180,7 @@ const CanvasImageContent = forwardRef<
maxRetries = 2,
delayRenderRetries,
delayRenderTimeoutInMilliseconds,
+ ...canvasProps
},
ref,
) => {
@@ -363,6 +364,7 @@ const CanvasImageContent = forwardRef<
return (
<canvas
+ {...canvasProps}
ref={canvasRef}
width={width}
height={height}
@@ -404,6 +406,8 @@ const CanvasImageInner = forwardRef<
showInTimeline,
stack,
_experimentalControls: controls,
+ _remotionInternalDocumentationLink,
+ ...canvasProps
},
ref,
) => {
@@ -421,6 +425,12 @@ const CanvasImageInner = forwardRef<
hidden={hidden}
showInTimeline={showInTimeline ?? true}
name={name ?? '<CanvasImage>'}
+ _remotionInternalDocumentationLink={
+ _remotionInternalDocumentationLink ??
+ (name === undefined
+ ? 'https://www.remotion.dev/docs/canvasimage'
+ : undefined)
+ }
_experimentalControls={controls}
_remotionInternalEffects={memoizedEffectDefinitions}
_remotionInternalIsMedia={{type: 'image', src}}
@@ -442,6 +452,7 @@ const CanvasImageInner = forwardRef<
maxRetries={maxRetries}
delayRenderRetries={delayRenderRetries}
delayRenderTimeoutInMilliseconds={delayRenderTimeoutInMilliseconds}
+ {...canvasProps}
/>
</Sequence>
);
diff --git a/packages/core/src/canvas-image/props.ts b/packages/core/src/canvas-image/props.ts
index 6191d5862f..ce8d172db5 100644
--- a/packages/core/src/canvas-image/props.ts
+++ b/packages/core/src/canvas-image/props.ts
@@ -13,18 +13,28 @@ type CanvasImageSequenceProps = Pick<
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;
- readonly pauseWhenLoading?: boolean;
- readonly maxRetries?: number;
- readonly delayRenderRetries?: number;
- readonly delayRenderTimeoutInMilliseconds?: number;
-};
+export type CanvasImageCanvasProps = Omit<
+ React.CanvasHTMLAttributes<HTMLCanvasElement>,
+ 'children' | 'height' | 'onError' | 'width'
+>;
+
+export type CanvasImageProps = CanvasImageSequenceProps &
+ CanvasImageCanvasProps & {
+ 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;
+ readonly pauseWhenLoading?: boolean;
+ readonly maxRetries?: number;
+ readonly delayRenderRetries?: number;
+ readonly delayRenderTimeoutInMilliseconds?: number;
+ /**
+ * @deprecated For internal use only.
+ */
+ readonly _remotionInternalDocumentationLink?: string;
+ };
diff --git a/packages/core/src/test/Img.test.tsx b/packages/core/src/test/Img.test.tsx
index 53687c2f36..2619b2a676 100644
--- a/packages/core/src/test/Img.test.tsx
+++ b/packages/core/src/test/Img.test.tsx
@@ -1,5 +1,5 @@
import {afterEach, beforeEach, expect, test} from 'bun:test';
-import {cleanup, render, waitFor} from '@testing-library/react';
+import {cleanup, fireEvent, render, waitFor} from '@testing-library/react';
import React from 'react';
import type {
EffectApplyParams,
@@ -204,6 +204,41 @@ test('Img throws when native image props conflict with effects', () => {
);
});
+test('Img forwards canvas-compatible attributes when effects are passed', async () => {
+ const onClick = () => {
+ drawImageCalls.push(['clicked']);
+ };
+ const {container} = renderImg(
+ <Img
+ src={testImgUrl}
+ width={100}
+ height={50}
+ effects={[makeEffect()]}
+ aria-label="Image with effects"
+ data-testid="img-effects-canvas"
+ role="img"
+ tabIndex={0}
+ title="Canvas image"
+ onClick={onClick}
+ />,
+ );
+
+ const canvas = container.querySelector('canvas');
+
+ await waitFor(() => {
+ expect(canvas?.width).toBe(100);
+ });
+
+ expect(canvas?.getAttribute('aria-label')).toBe('Image with effects');
+ expect(canvas?.getAttribute('data-testid')).toBe('img-effects-canvas');
+ expect(canvas?.getAttribute('role')).toBe('img');
+ expect(canvas?.getAttribute('tabindex')).toBe('0');
+ expect(canvas?.getAttribute('title')).toBe('Canvas image');
+
+ fireEvent.click(canvas as HTMLCanvasElement);
+ expect(drawImageCalls.some((call) => call[0] === 'clicked')).toBe(true);
+});
+
test('Img throws when a ref is passed together with effects', () => {
const ref = React.createRef<HTMLImageElement>();
diff --git a/packages/docs/docs/img.mdx b/packages/docs/docs/img.mdx
index fa4a40bd34..e3c42a9168 100644
--- a/packages/docs/docs/img.mdx
+++ b/packages/docs/docs/img.mdx
@@ -45,7 +45,7 @@ export const MyComp: React.FC = () => {
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).
+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) and outputs a `<canvas>`.
```tsx twoslash title="MyComp.tsx"
import {AbsoluteFill, Img, staticFile} from 'remotion';
@@ -64,6 +64,14 @@ Because the element becomes a `<canvas>`, native image props that require an `<i
The unsupported props include `ref`, `srcSet`, `sizes`, `loading`, `decoding`, `fetchPriority`, `useMap`, `crossOrigin`, `onLoad`, `onError`, `onImageFrame` and `alt`.
+Canvas-compatible props such as `aria-*`, `data-*`, `role`, `title`, `tabIndex` and pointer or mouse event handlers are forwarded to the underlying `<canvas>`.
+
+### `fit?`<AvailableFrom v="4.0.468" />
+
+Controls how the image is drawn into the canvas when [`effects`](#effects) is a non-empty array.
+
+Can be `"fill"`, `"contain"` or `"cover"`. Default: `"fill"`.
+
### `onError`
To use the `<Img>` tag in a resilient way, handle the error that occurs when an image can not be loaded:
diff --git a/packages/example/src/Root.tsx b/packages/example/src/Root.tsx
index 56ca69a7fd..e66201560c 100644
--- a/packages/example/src/Root.tsx
+++ b/packages/example/src/Root.tsx
@@ -220,6 +220,7 @@ import {PremountOnTransitionSeries} from './PremountOnTransitionSeries';
import {PrintProps} from './PrintProps';
import {SfxExample} from './Sfx';
import {CanvasImg} from './SimpleImg/CanvasImg';
+import {ImgEffects} from './SimpleImg/ImgEffects';
import {SmoothTextTransition} from './SmoothTextTransition';
import {SpringSeason} from './SpringSeason';
import {StarburstExample} from './Starburst';
@@ -561,6 +562,14 @@ export const Index: React.FC = () => {
fps={30}
durationInFrames={10}
/>
+ <Composition
+ id="img-effects"
+ component={ImgEffects}
+ width={1080}
+ height={1080}
+ fps={30}
+ durationInFrames={10}
+ />
<Composition
id="missing-img"
component={MissingImg}
diff --git a/packages/example/src/SimpleImg/ImgEffects.tsx b/packages/example/src/SimpleImg/ImgEffects.tsx
new file mode 100644
index 0000000000..c0715bb578
--- /dev/null
+++ b/packages/example/src/SimpleImg/ImgEffects.tsx
@@ -0,0 +1,61 @@
+import {blur} from '@remotion/effects/blur';
+import {halftone} from '@remotion/effects/halftone';
+import {tint} from '@remotion/effects/tint';
+import React from 'react';
+import {AbsoluteFill, Img, staticFile} from 'remotion';
+
+const tileStyle: React.CSSProperties = {
+ flex: 1,
+ borderRadius: 32,
+ overflow: 'hidden',
+ border: '4px solid white',
+ boxShadow: '0 24px 80px rgba(0, 0, 0, 0.35)',
+};
+
+const imageStyle: React.CSSProperties = {
+ width: '100%',
+ height: '100%',
+};
+
+export const ImgEffects = (): React.ReactNode => {
+ return (
+ <AbsoluteFill
+ style={{
+ background: 'linear-gradient(135deg, #111827, #312e81)',
+ padding: 64,
+ gap: 40,
+ flexDirection: 'row',
+ }}
+ >
+ <div style={tileStyle}>
+ <Img
+ src={staticFile('1.jpg')}
+ width={450}
+ height={720}
+ fit="cover"
+ style={imageStyle}
+ effects={[tint({color: '#38bdf8', amount: 0.45})]}
+ aria-label="Tinted image"
+ />
+ </div>
+ <div style={tileStyle}>
+ <Img
+ src={staticFile('1.jpg')}
+ width={450}
+ height={720}
+ fit="cover"
+ style={imageStyle}
+ effects={[
+ blur({radius: 6}),
+ halftone({
+ shape: 'circle',
+ dotSize: 14,
+ dotSpacing: 14,
+ }),
+ ]}
+ aria-label="Blurred halftone image"
+ />
+ </div>
+ </AbsoluteFill>
+ );
+};