Skip to content

🎥 Make videos programmatically with React

`@remotion/web-renderer`: Support `object-fit` CSS property

JonnyBurger8aa6f86335a9
diff --git a/packages/docs/docs/client-side-rendering/limitations.mdx b/packages/docs/docs/client-side-rendering/limitations.mdx
index cc24d5408c..0d6b0b9246 100644
--- a/packages/docs/docs/client-side-rendering/limitations.mdx
+++ b/packages/docs/docs/client-side-rendering/limitations.mdx
@@ -20,7 +20,8 @@ It is not feasible to support all CSS properties and factors affecting the visua
Properties such as `margin`, `left`, `display`, `width`, `height`, `flex`, `flex-direction` affect the position and size of the element. Those are all <a style={{color: 'green'}}>supported</a> because Remotion uses [`.getBoundingClientRect()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect) to obtain the position and size of the element.
-The `overflow` property is <a style={{color: 'green'}}>supported</a>.
+The `overflow` property is <a style={{color: 'green'}}>supported</a>.
+The `object-fit` property is <a style={{color: 'green'}}>supported</a>.
### Transformations
@@ -105,7 +106,6 @@ Here is a selection of unsupported styles:
- `backdrop-filter`
- `mix-blend-mode`
- `background-blend-mode`
-- `object-fit`
- `backface-visibility`
- `z-index`
- See [Z-indexing](#z-indexing) below.
diff --git a/packages/web-renderer/src/drawing/calculate-object-fit.ts b/packages/web-renderer/src/drawing/calculate-object-fit.ts
new file mode 100644
index 0000000000..3d9e3f0c92
--- /dev/null
+++ b/packages/web-renderer/src/drawing/calculate-object-fit.ts
@@ -0,0 +1,260 @@
+export type ObjectFit = 'fill' | 'contain' | 'cover' | 'none' | 'scale-down';
+
+export type ObjectFitResult = {
+ // Source rectangle (which part of the image to draw)
+ sourceX: number;
+ sourceY: number;
+ sourceWidth: number;
+ sourceHeight: number;
+ // Destination rectangle (where to draw on canvas)
+ destX: number;
+ destY: number;
+ destWidth: number;
+ destHeight: number;
+};
+
+type ObjectFitParams = {
+ containerSize: {width: number; height: number; left: number; top: number};
+ intrinsicSize: {width: number; height: number};
+};
+
+/**
+ * fill: Stretch the image to fill the container, ignoring aspect ratio
+ */
+const calculateFill = ({
+ containerSize,
+ intrinsicSize,
+}: ObjectFitParams): ObjectFitResult => {
+ return {
+ sourceX: 0,
+ sourceY: 0,
+ sourceWidth: intrinsicSize.width,
+ sourceHeight: intrinsicSize.height,
+ destX: containerSize.left,
+ destY: containerSize.top,
+ destWidth: containerSize.width,
+ destHeight: containerSize.height,
+ };
+};
+
+/**
+ * contain: Scale the image to fit inside the container while maintaining aspect ratio.
+ * This may result in letterboxing (empty space on sides or top/bottom).
+ */
+const calculateContain = ({
+ containerSize,
+ intrinsicSize,
+}: ObjectFitParams): ObjectFitResult => {
+ const containerAspect = containerSize.width / containerSize.height;
+ const imageAspect = intrinsicSize.width / intrinsicSize.height;
+
+ let destWidth: number;
+ let destHeight: number;
+
+ if (imageAspect > containerAspect) {
+ // Image is wider than container (relative to their heights)
+ // Fit by width, letterbox top/bottom
+ destWidth = containerSize.width;
+ destHeight = containerSize.width / imageAspect;
+ } else {
+ // Image is taller than container (relative to their widths)
+ // Fit by height, letterbox left/right
+ destHeight = containerSize.height;
+ destWidth = containerSize.height * imageAspect;
+ }
+
+ // Center the image in the container
+ const destX = containerSize.left + (containerSize.width - destWidth) / 2;
+ const destY = containerSize.top + (containerSize.height - destHeight) / 2;
+
+ return {
+ sourceX: 0,
+ sourceY: 0,
+ sourceWidth: intrinsicSize.width,
+ sourceHeight: intrinsicSize.height,
+ destX,
+ destY,
+ destWidth,
+ destHeight,
+ };
+};
+
+/**
+ * cover: Scale the image to cover the container while maintaining aspect ratio.
+ * Parts of the image may be cropped.
+ */
+const calculateCover = ({
+ containerSize,
+ intrinsicSize,
+}: ObjectFitParams): ObjectFitResult => {
+ const containerAspect = containerSize.width / containerSize.height;
+ const imageAspect = intrinsicSize.width / intrinsicSize.height;
+
+ let sourceX = 0;
+ let sourceY = 0;
+ let sourceWidth = intrinsicSize.width;
+ let sourceHeight = intrinsicSize.height;
+
+ if (imageAspect > containerAspect) {
+ // Image is wider than container - crop horizontally
+ // Scale by height, then crop width
+ sourceWidth = intrinsicSize.height * containerAspect;
+ sourceX = (intrinsicSize.width - sourceWidth) / 2;
+ } else {
+ // Image is taller than container - crop vertically
+ // Scale by width, then crop height
+ sourceHeight = intrinsicSize.width / containerAspect;
+ sourceY = (intrinsicSize.height - sourceHeight) / 2;
+ }
+
+ return {
+ sourceX,
+ sourceY,
+ sourceWidth,
+ sourceHeight,
+ destX: containerSize.left,
+ destY: containerSize.top,
+ destWidth: containerSize.width,
+ destHeight: containerSize.height,
+ };
+};
+
+/**
+ * none: Draw the image at its natural size, centered in the container.
+ * Clips to the container bounds if the image overflows.
+ */
+const calculateNone = ({
+ containerSize,
+ intrinsicSize,
+}: ObjectFitParams): ObjectFitResult => {
+ // Calculate centered position (can be negative if image is larger than container)
+ const centeredX =
+ containerSize.left + (containerSize.width - intrinsicSize.width) / 2;
+ const centeredY =
+ containerSize.top + (containerSize.height - intrinsicSize.height) / 2;
+
+ // Calculate clipping bounds
+ let sourceX = 0;
+ let sourceY = 0;
+ let sourceWidth = intrinsicSize.width;
+ let sourceHeight = intrinsicSize.height;
+ let destX = centeredX;
+ let destY = centeredY;
+ let destWidth = intrinsicSize.width;
+ let destHeight = intrinsicSize.height;
+
+ // Clip left edge
+ if (destX < containerSize.left) {
+ const clipAmount = containerSize.left - destX;
+ sourceX = clipAmount;
+ sourceWidth -= clipAmount;
+ destX = containerSize.left;
+ destWidth -= clipAmount;
+ }
+
+ // Clip top edge
+ if (destY < containerSize.top) {
+ const clipAmount = containerSize.top - destY;
+ sourceY = clipAmount;
+ sourceHeight -= clipAmount;
+ destY = containerSize.top;
+ destHeight -= clipAmount;
+ }
+
+ // Clip right edge
+ const containerRight = containerSize.left + containerSize.width;
+ if (destX + destWidth > containerRight) {
+ const clipAmount = destX + destWidth - containerRight;
+ sourceWidth -= clipAmount;
+ destWidth -= clipAmount;
+ }
+
+ // Clip bottom edge
+ const containerBottom = containerSize.top + containerSize.height;
+ if (destY + destHeight > containerBottom) {
+ const clipAmount = destY + destHeight - containerBottom;
+ sourceHeight -= clipAmount;
+ destHeight -= clipAmount;
+ }
+
+ return {
+ sourceX,
+ sourceY,
+ sourceWidth,
+ sourceHeight,
+ destX,
+ destY,
+ destWidth,
+ destHeight,
+ };
+};
+
+/**
+ * Calculates how to draw an image based on object-fit CSS property.
+ *
+ * @param objectFit - The CSS object-fit value
+ * @param containerSize - The container dimensions (where the image should be drawn)
+ * @param intrinsicSize - The natural/intrinsic size of the image
+ * @returns Source and destination rectangles for drawImage
+ */
+export const calculateObjectFit = ({
+ objectFit,
+ containerSize,
+ intrinsicSize,
+}: {
+ objectFit: ObjectFit;
+} & ObjectFitParams): ObjectFitResult => {
+ switch (objectFit) {
+ case 'fill':
+ return calculateFill({containerSize, intrinsicSize});
+
+ case 'contain':
+ return calculateContain({containerSize, intrinsicSize});
+
+ case 'cover':
+ return calculateCover({containerSize, intrinsicSize});
+
+ case 'none':
+ return calculateNone({containerSize, intrinsicSize});
+
+ case 'scale-down': {
+ // scale-down behaves like contain or none, whichever results in a smaller image
+ const containResult = calculateContain({containerSize, intrinsicSize});
+ const noneResult = calculateNone({containerSize, intrinsicSize});
+
+ // Compare the rendered size - use whichever is smaller
+ const containArea = containResult.destWidth * containResult.destHeight;
+ const noneArea = noneResult.destWidth * noneResult.destHeight;
+
+ return containArea < noneArea ? containResult : noneResult;
+ }
+
+ default: {
+ const exhaustiveCheck: never = objectFit;
+ throw new Error(`Unknown object-fit value: ${exhaustiveCheck}`);
+ }
+ }
+};
+
+/**
+ * Parse an object-fit CSS value string into our ObjectFit type.
+ * Returns 'fill' as the default if the value is not recognized.
+ */
+export const parseObjectFit = (value: string | null | undefined): ObjectFit => {
+ if (!value) {
+ return 'fill';
+ }
+
+ const normalized = value.trim().toLowerCase();
+
+ switch (normalized) {
+ case 'fill':
+ case 'contain':
+ case 'cover':
+ case 'none':
+ case 'scale-down':
+ return normalized;
+ default:
+ return 'fill';
+ }
+};
diff --git a/packages/web-renderer/src/drawing/draw-dom-element.ts b/packages/web-renderer/src/drawing/draw-dom-element.ts
index 2c5edc7f27..2b16cd8605 100644
--- a/packages/web-renderer/src/drawing/draw-dom-element.ts
+++ b/packages/web-renderer/src/drawing/draw-dom-element.ts
@@ -1,3 +1,4 @@
+import {calculateObjectFit, parseObjectFit} from './calculate-object-fit';
import type {DrawFn} from './drawn-fn';
import {fitSvgIntoItsContainer} from './fit-svg-into-its-dimensions';
import {turnSvgIntoDrawable} from './turn-svg-into-drawable';
@@ -30,45 +31,115 @@ const getReadableImageError = (
return null;
};
-export const drawDomElement = (node: HTMLElement | SVGElement) => {
- const domDrawFn: DrawFn = async ({dimensions, contextToDraw}) => {
- const drawable = await (node instanceof SVGSVGElement
- ? turnSvgIntoDrawable(node)
- : node instanceof HTMLImageElement
- ? node
- : node instanceof HTMLCanvasElement
- ? node
- : null);
+/**
+ * Draw an SVG element using "contain" behavior (the default for SVGs).
+ */
+const drawSvg = ({
+ drawable,
+ dimensions,
+ contextToDraw,
+}: {
+ drawable: HTMLImageElement;
+ dimensions: DOMRect;
+ contextToDraw: OffscreenCanvasRenderingContext2D;
+}) => {
+ const fitted = fitSvgIntoItsContainer({
+ containerSize: dimensions,
+ elementSize: {
+ width: drawable.width,
+ height: drawable.height,
+ },
+ });
+ contextToDraw.drawImage(
+ drawable,
+ fitted.left,
+ fitted.top,
+ fitted.width,
+ fitted.height,
+ );
+};
+
+/**
+ * Draw an image or canvas element using the object-fit CSS property.
+ */
+const drawReplacedElement = ({
+ drawable,
+ dimensions,
+ computedStyle,
+ contextToDraw,
+}: {
+ drawable: HTMLImageElement | HTMLCanvasElement;
+ dimensions: DOMRect;
+ computedStyle: CSSStyleDeclaration;
+ contextToDraw: OffscreenCanvasRenderingContext2D;
+}) => {
+ const objectFit = parseObjectFit(computedStyle.objectFit);
+
+ const intrinsicSize =
+ drawable instanceof HTMLImageElement
+ ? {width: drawable.naturalWidth, height: drawable.naturalHeight}
+ : {width: drawable.width, height: drawable.height};
+
+ const result = calculateObjectFit({
+ objectFit,
+ containerSize: {
+ width: dimensions.width,
+ height: dimensions.height,
+ left: dimensions.left,
+ top: dimensions.top,
+ },
+ intrinsicSize,
+ });
- if (!drawable) {
+ // Use the 9-argument drawImage to support source cropping (for cover mode)
+ contextToDraw.drawImage(
+ drawable,
+ result.sourceX,
+ result.sourceY,
+ result.sourceWidth,
+ result.sourceHeight,
+ result.destX,
+ result.destY,
+ result.destWidth,
+ result.destHeight,
+ );
+};
+
+export const drawDomElement = (node: HTMLElement | SVGElement) => {
+ const domDrawFn: DrawFn = async ({
+ dimensions,
+ contextToDraw,
+ computedStyle,
+ }) => {
+ // Handle SVG elements separately - they use "contain" behavior by default
+ if (node instanceof SVGSVGElement) {
+ const drawable = await turnSvgIntoDrawable(node);
+ drawSvg({drawable, dimensions, contextToDraw});
return;
}
- try {
- const fitted = fitSvgIntoItsContainer({
- containerSize: dimensions,
- elementSize: {
- width: drawable.width,
- height: drawable.height,
- },
- });
- contextToDraw.drawImage(
- drawable,
- fitted.left,
- fitted.top,
- fitted.width,
- fitted.height,
- );
- } catch (err) {
- // Provide readable error messages for image errors
- if (node instanceof HTMLImageElement) {
- const readableError = getReadableImageError(err, node);
- if (readableError) {
- throw readableError;
+ // Handle replaced elements (img, canvas) with object-fit support
+ if (
+ node instanceof HTMLImageElement ||
+ node instanceof HTMLCanvasElement
+ ) {
+ try {
+ drawReplacedElement({
+ drawable: node,
+ dimensions,
+ computedStyle,
+ contextToDraw,
+ });
+ } catch (err) {
+ if (node instanceof HTMLImageElement) {
+ const readableError = getReadableImageError(err, node);
+ if (readableError) {
+ throw readableError;
+ }
}
- }
- throw err;
+ throw err;
+ }
}
};
diff --git a/packages/web-renderer/src/test/Root.tsx b/packages/web-renderer/src/test/Root.tsx
index 112667ea74..b415c9af52 100644
--- a/packages/web-renderer/src/test/Root.tsx
+++ b/packages/web-renderer/src/test/Root.tsx
@@ -26,6 +26,7 @@ import {lineHeight} from './fixtures/line-height';
import {linearGradient} from './fixtures/linear-gradient';
import {manyLayers} from './fixtures/many-layers';
import {maskImage} from './fixtures/mask-image';
+import {objectFit} from './fixtures/object-fit';
import {multiLevelTransformOrigins} from './fixtures/multi-level-transform-origins';
import {nestedTranslateScale} from './fixtures/nested-translate-scale';
import {opacityInherited} from './fixtures/opacity-inherited';
@@ -81,6 +82,7 @@ export const Root: React.FC = () => {
<Composition {...overflowHidden} />
<Composition {...overflowHidden3dTransform} />
<Composition {...hugeImageTransform} />
+ <Composition {...objectFit} />
<Composition {...nestedTranslateScale} />
<Composition {...scaledTranslatedSvg} />
<Composition {...svgExplicitDimensions} />
diff --git a/packages/web-renderer/src/test/__screenshots__/object-fit.test.tsx/object-fit-chromium-darwin.png b/packages/web-renderer/src/test/__screenshots__/object-fit.test.tsx/object-fit-chromium-darwin.png
new file mode 100644
index 0000000000..a45f2a2b97
Binary files /dev/null and b/packages/web-renderer/src/test/__screenshots__/object-fit.test.tsx/object-fit-chromium-darwin.png differ
diff --git a/packages/web-renderer/src/test/__screenshots__/object-fit.test.tsx/object-fit-firefox-darwin.png b/packages/web-renderer/src/test/__screenshots__/object-fit.test.tsx/object-fit-firefox-darwin.png
new file mode 100644
index 0000000000..3198d2bca0
Binary files /dev/null and b/packages/web-renderer/src/test/__screenshots__/object-fit.test.tsx/object-fit-firefox-darwin.png differ
diff --git a/packages/web-renderer/src/test/__screenshots__/object-fit.test.tsx/object-fit-webkit-darwin.png b/packages/web-renderer/src/test/__screenshots__/object-fit.test.tsx/object-fit-webkit-darwin.png
new file mode 100644
index 0000000000..5a60fc4261
Binary files /dev/null and b/packages/web-renderer/src/test/__screenshots__/object-fit.test.tsx/object-fit-webkit-darwin.png differ
diff --git a/packages/web-renderer/src/test/fixtures/object-fit.tsx b/packages/web-renderer/src/test/fixtures/object-fit.tsx
new file mode 100644
index 0000000000..e329488c3d
--- /dev/null
+++ b/packages/web-renderer/src/test/fixtures/object-fit.tsx
@@ -0,0 +1,140 @@
+import {AbsoluteFill, Img, staticFile} from 'remotion';
+
+const Component: React.FC = () => {
+ return (
+ <AbsoluteFill
+ style={{
+ backgroundColor: '#f0f0f0',
+ display: 'grid',
+ gridTemplateColumns: 'repeat(3, 1fr)',
+ gridTemplateRows: 'repeat(2, 1fr)',
+ gap: 10,
+ padding: 10,
+ }}
+ >
+ {/* fill - stretches to fill the container */}
+ <div style={{backgroundColor: '#e0e0e0', position: 'relative'}}>
+ <Img
+ src={staticFile('1.webp')}
+ style={{
+ width: '100%',
+ height: '100%',
+ objectFit: 'fill',
+ }}
+ />
+ <div
+ style={{
+ position: 'absolute',
+ top: 5,
+ left: 5,
+ fontSize: 12,
+ fontWeight: 'bold',
+ }}
+ >
+ fill
+ </div>
+ </div>
+
+ {/* contain - maintains aspect ratio, fits inside */}
+ <div style={{backgroundColor: '#e0e0e0', position: 'relative'}}>
+ <Img
+ src={staticFile('1.webp')}
+ style={{
+ width: '100%',
+ height: '100%',
+ objectFit: 'contain',
+ }}
+ />
+ <div
+ style={{
+ position: 'absolute',
+ top: 5,
+ left: 5,
+ fontSize: 12,
+ fontWeight: 'bold',
+ }}
+ >
+ contain
+ </div>
+ </div>
+
+ {/* cover - maintains aspect ratio, covers container */}
+ <div style={{backgroundColor: '#e0e0e0', position: 'relative'}}>
+ <Img
+ src={staticFile('1.webp')}
+ style={{
+ width: '100%',
+ height: '100%',
+ objectFit: 'cover',
+ }}
+ />
+ <div
+ style={{
+ position: 'absolute',
+ top: 5,
+ left: 5,
+ fontSize: 12,
+ fontWeight: 'bold',
+ }}
+ >
+ cover
+ </div>
+ </div>
+
+ {/* none - original size, not resized */}
+ <div style={{backgroundColor: '#e0e0e0', position: 'relative'}}>
+ <Img
+ src={staticFile('1.webp')}
+ style={{
+ width: '100%',
+ height: '100%',
+ objectFit: 'none',
+ }}
+ />
+ <div
+ style={{
+ position: 'absolute',
+ top: 5,
+ left: 5,
+ fontSize: 12,
+ fontWeight: 'bold',
+ }}
+ >
+ none
+ </div>
+ </div>
+
+ {/* scale-down - behaves like none or contain, whichever is smaller */}
+ <div style={{backgroundColor: '#e0e0e0', position: 'relative'}}>
+ <Img
+ src={staticFile('1.webp')}
+ style={{
+ width: '100%',
+ height: '100%',
+ objectFit: 'scale-down',
+ }}
+ />
+ <div
+ style={{
+ position: 'absolute',
+ top: 5,
+ left: 5,
+ fontSize: 12,
+ fontWeight: 'bold',
+ }}
+ >
+ scale-down
+ </div>
+ </div>
+ </AbsoluteFill>
+ );
+};
+
+export const objectFit = {
+ component: Component,
+ id: 'object-fit',
+ width: 600,
+ height: 400,
+ fps: 25,
+ durationInFrames: 1,
+} as const;
diff --git a/packages/web-renderer/src/test/object-fit.test.tsx b/packages/web-renderer/src/test/object-fit.test.tsx
new file mode 100644
index 0000000000..a87e0a9aa7
--- /dev/null
+++ b/packages/web-renderer/src/test/object-fit.test.tsx
@@ -0,0 +1,16 @@
+import {test} from 'vitest';
+import {renderStillOnWeb} from '../render-still-on-web';
+import {objectFit} from './fixtures/object-fit';
+import {testImage} from './utils';
+
+test('should render object-fit values correctly', async () => {
+ const {blob} = await renderStillOnWeb({
+ licenseKey: 'free-license',
+ composition: objectFit,
+ frame: 0,
+ inputProps: {},
+ imageFormat: 'png',
+ });
+
+ await testImage({blob, testId: 'object-fit'});
+});