Skip to content

πŸŽ₯ Make videos programmatically with React

`remotion`: Add Sequence crop controls (#9670)

Jonny Burger1f8a076843c3
diff --git a/packages/core/src/HtmlInCanvas.tsx b/packages/core/src/HtmlInCanvas.tsx
index 8518b2b9e6..0c8375cc4f 100644
--- a/packages/core/src/HtmlInCanvas.tsx
+++ b/packages/core/src/HtmlInCanvas.tsx
@@ -16,16 +16,21 @@ import {
useMemoizedEffects,
} from './effects/use-memoized-effects.js';
import {addSequenceStackTraces} from './enable-sequence-stack-traces.js';
-import type {InteractiveBaseProps} from './Interactive.js';
+import type {
+ InteractiveBaseProps,
+ InteractiveCropProps,
+} from './Interactive.js';
import {
backgroundSchema,
baseSchema,
borderSchema,
+ cropSchema,
transformSchema,
type InteractivitySchema,
} from './interactivity-schema.js';
import type {AbsoluteFillLayout} from './Sequence.js';
import {Sequence} from './Sequence.js';
+import {useCropStyle} from './use-crop-style.js';
import {useDelayRender} from './use-delay-render.js';
import {useRemotionEnvironment} from './use-remotion-environment.js';
import {withInteractivitySchema} from './with-interactivity-schema.js';
@@ -311,6 +316,7 @@ const defaultOnPaint = ({
/* eslint-disable react/require-default-props -- optional fields mirror `<Sequence>` / canvas hooks API */
export type HtmlInCanvasProps = Omit<InteractiveBaseProps, 'children'> &
+ InteractiveCropProps &
Omit<
AbsoluteFillLayout,
| 'layout'
@@ -723,6 +729,10 @@ const HtmlInCanvasInner = forwardRef<
pixelDensity,
controls,
style,
+ cropLeft,
+ cropRight,
+ cropTop,
+ cropBottom,
durationInFrames,
name,
...sequenceProps
@@ -742,6 +752,14 @@ const HtmlInCanvasInner = forwardRef<
},
[ref],
);
+ const croppedStyle = useCropStyle({
+ cropLeft,
+ cropRight,
+ cropTop,
+ cropBottom,
+ style: style ?? null,
+ componentName: '<HtmlInCanvas />',
+ });
return (
<Sequence
@@ -763,7 +781,7 @@ const HtmlInCanvasInner = forwardRef<
onInit={onInit}
pixelDensity={pixelDensity}
controls={controls}
- style={style}
+ style={croppedStyle ?? undefined}
>
{children}
</HtmlInCanvasContent>
@@ -788,6 +806,7 @@ export const htmlInCanvasSchema = {
...transformSchema,
...backgroundSchema,
...borderSchema,
+ ...cropSchema,
} as const satisfies InteractivitySchema;
const HtmlInCanvasWrapped = withInteractivitySchema({
diff --git a/packages/core/src/Img.tsx b/packages/core/src/Img.tsx
index a1488d4754..697cf12cee 100644
--- a/packages/core/src/Img.tsx
+++ b/packages/core/src/Img.tsx
@@ -19,12 +19,14 @@ import {Freeze} from './freeze.js';
import {getCrossOriginValue} from './get-cross-origin-value.js';
import type {
InteractiveBaseProps,
+ InteractiveCropProps,
InteractivePremountProps,
} from './Interactive.js';
import {
backgroundSchema,
baseSchema,
borderSchema,
+ cropSchema,
premountSchema,
transformSchema,
type InteractivitySchema,
@@ -34,6 +36,7 @@ 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 {useCropStyle} from './use-crop-style.js';
import {useDelayRender} from './use-delay-render.js';
import {usePremounting} from './use-premounting.js';
import {useRemotionEnvironment} from './use-remotion-environment.js';
@@ -67,6 +70,7 @@ export type ImgProps = NativeImgProps & {
*/
readonly stack?: string;
} & InteractiveBaseProps &
+ InteractiveCropProps &
InteractivePremountProps;
type Expected = Omit<
@@ -89,6 +93,10 @@ type ImgContentProps = Omit<
| 'postmountFor'
| 'styleWhilePremounted'
| 'styleWhilePostmounted'
+ | 'cropLeft'
+ | 'cropRight'
+ | 'cropTop'
+ | 'cropBottom'
> & {
readonly refForOutline: React.RefObject<HTMLElement | null>;
};
@@ -361,6 +369,10 @@ const NativeImgInner: React.FC<NativeImgInnerProps> = ({
style,
styleWhilePremounted,
styleWhilePostmounted,
+ cropLeft,
+ cropRight,
+ cropTop,
+ cropBottom,
controls,
outlineRef: refForOutline,
...props
@@ -387,6 +399,14 @@ const NativeImgInner: React.FC<NativeImgInnerProps> = ({
styleWhilePostmounted: styleWhilePostmounted ?? null,
hideWhilePremounted: 'display-none',
});
+ const croppedStyle = useCropStyle({
+ cropLeft,
+ cropRight,
+ cropTop,
+ cropBottom,
+ style: premountingStyle,
+ componentName: '<Img />',
+ });
return (
<Freeze frame={freezeFrame} active={isPremountingOrPostmounting}>
@@ -412,7 +432,7 @@ const NativeImgInner: React.FC<NativeImgInnerProps> = ({
<ImgContent
src={src}
refForOutline={refForOutline}
- style={premountingStyle ?? undefined}
+ style={croppedStyle ?? undefined}
{...props}
/>
</Sequence>
@@ -435,6 +455,7 @@ export const imgSchema = {
keyframable: false,
},
...baseSchema,
+ ...cropSchema,
...premountSchema,
...transformSchema,
...backgroundSchema,
@@ -541,6 +562,10 @@ const ImgInner: React.FC<
height,
className,
style,
+ cropLeft,
+ cropRight,
+ cropTop,
+ cropBottom,
id,
pauseWhenLoading,
maxRetries,
@@ -574,6 +599,10 @@ const ImgInner: React.FC<
height={height}
className={className}
style={style}
+ cropLeft={cropLeft}
+ cropRight={cropRight}
+ cropTop={cropTop}
+ cropBottom={cropBottom}
id={id}
pauseWhenLoading={shouldPauseWhenLoading}
maxRetries={maxRetries}
@@ -609,6 +638,10 @@ const ImgInner: React.FC<
effects={effects}
className={className}
style={style}
+ cropLeft={cropLeft}
+ cropRight={cropRight}
+ cropTop={cropTop}
+ cropBottom={cropBottom}
id={id}
pauseWhenLoading={shouldPauseWhenLoading}
maxRetries={maxRetries}
@@ -627,6 +660,7 @@ const ImgInner: React.FC<
showInTimeline={showInTimeline}
stack={stack}
_remotionInternalDocumentationLink="https://www.remotion.dev/docs/img"
+ _remotionInternalCropComponentName="<Img />"
controls={controls}
outlineRef={refForOutline}
{...canvasProps}
diff --git a/packages/core/src/Interactive.tsx b/packages/core/src/Interactive.tsx
index 00670fcd19..86356a584e 100644
--- a/packages/core/src/Interactive.tsx
+++ b/packages/core/src/Interactive.tsx
@@ -8,6 +8,7 @@ import {
backgroundSchema,
baseSchema,
borderSchema,
+ cropSchema,
premountSchema,
sequenceSchema,
svgPaintSchema,
@@ -85,6 +86,11 @@ export type InteractiveBaseProps = Pick<
export type InteractiveTransformProps = Pick<AbsoluteFillLayout, 'style'>;
+export type InteractiveCropProps = Pick<
+ SequenceProps,
+ 'cropLeft' | 'cropRight' | 'cropTop' | 'cropBottom'
+>;
+
export type InteractivePremountProps = Pick<
AbsoluteFillLayout,
| 'premountFor'
@@ -315,6 +321,7 @@ export const Interactive = {
textSchema,
backgroundSchema,
borderSchema,
+ cropSchema,
svgPaintSchema,
svgStrokeSchema,
premountSchema,
diff --git a/packages/core/src/Sequence.tsx b/packages/core/src/Sequence.tsx
index f8ac0631e3..758cc4d8c5 100644
--- a/packages/core/src/Sequence.tsx
+++ b/packages/core/src/Sequence.tsx
@@ -17,6 +17,11 @@ import {
sequenceSchemaWithoutFrom,
} from './interactivity-schema.js';
import {useNonce} from './nonce.js';
+import {
+ getSequenceCropClipPath,
+ resolveSequenceCrop,
+ validateSequenceCrop,
+} from './sequence-crop.js';
import type {SequenceContextType} from './SequenceContext.js';
import {SequenceContext} from './SequenceContext.js';
import {SequenceManager} from './SequenceManager.js';
@@ -54,6 +59,10 @@ export type SequencePropsWithoutDuration = {
readonly children?: React.ReactNode;
readonly width?: number;
readonly height?: number;
+ readonly cropLeft?: number;
+ readonly cropRight?: number;
+ readonly cropTop?: number;
+ readonly cropBottom?: number;
readonly from?: number;
readonly trimBefore?: number;
readonly freeze?: number | null;
@@ -142,6 +151,10 @@ const RegularSequenceRefForwardingFunction: React.ForwardRefRenderFunction<
_remotionInternalPostmountDisplay: postmountDisplay,
_remotionInternalIsMedia: isMedia,
outlineRef: passedRefForOutline,
+ cropLeft,
+ cropRight,
+ cropTop,
+ cropBottom,
...other
},
ref,
@@ -162,6 +175,24 @@ const RegularSequenceRefForwardingFunction: React.ForwardRefRenderFunction<
);
}
+ const cropProps = {cropLeft, cropRight, cropTop, cropBottom};
+ const hasCropProp = Object.values(cropProps).some(
+ (value) => value !== undefined,
+ );
+
+ if (layout === 'none' && hasCropProp) {
+ throw new TypeError(
+ 'The cropLeft, cropRight, cropTop and cropBottom props of <Sequence /> are only supported with layout="absolute-fill".',
+ );
+ }
+
+ validateSequenceCrop(cropProps);
+ const {
+ left: resolvedCropLeft,
+ right: resolvedCropRight,
+ top: resolvedCropTop,
+ bottom: resolvedCropBottom,
+ } = resolveSequenceCrop(cropProps);
// @ts-expect-error
if (layout === 'none' && typeof other.style !== 'undefined') {
throw new TypeError(
@@ -518,6 +549,13 @@ const RegularSequenceRefForwardingFunction: React.ForwardRefRenderFunction<
);
const styleIfThere = other.layout === 'none' ? undefined : other.style;
+ const cropClipPath = getSequenceCropClipPath({
+ left: resolvedCropLeft,
+ right: resolvedCropRight,
+ top: resolvedCropTop,
+ bottom: resolvedCropBottom,
+ borderRadius: styleIfThere?.borderRadius,
+ });
const sequenceRef = useCallback(
(node: HTMLDivElement | null) => {
@@ -538,8 +576,13 @@ const RegularSequenceRefForwardingFunction: React.ForwardRefRenderFunction<
...(width ? {width} : {}),
...(height ? {height} : {}),
...(styleIfThere ?? {}),
+ ...(cropClipPath
+ ? {
+ clipPath: cropClipPath,
+ }
+ : {}),
};
- }, [height, styleIfThere, width]);
+ }, [cropClipPath, height, styleIfThere, width]);
if (ref !== null && layout === 'none') {
throw new TypeError(
diff --git a/packages/core/src/animated-image/AnimatedImage.tsx b/packages/core/src/animated-image/AnimatedImage.tsx
index 563dd36594..6846165f0c 100644
--- a/packages/core/src/animated-image/AnimatedImage.tsx
+++ b/packages/core/src/animated-image/AnimatedImage.tsx
@@ -20,11 +20,13 @@ import {
backgroundSchema,
baseSchema,
borderSchema,
+ cropSchema,
premountSchema,
transformSchema,
type InteractivitySchema,
} from '../interactivity-schema.js';
import {Sequence} from '../Sequence.js';
+import {useCropStyle} from '../use-crop-style.js';
import {useCurrentFrame} from '../use-current-frame.js';
import {useDelayRender} from '../use-delay-render.js';
import {usePremounting} from '../use-premounting.js';
@@ -51,6 +53,7 @@ export const animatedImageSchema = {
keyframable: false,
},
...baseSchema,
+ ...cropSchema,
...premountSchema,
playbackRate: {
type: 'number',
@@ -307,6 +310,10 @@ const AnimatedImageInner = ({
postmountFor,
styleWhilePremounted,
styleWhilePostmounted,
+ cropLeft,
+ cropRight,
+ cropTop,
+ cropBottom,
requestInit,
effects = [],
controls,
@@ -341,6 +348,14 @@ const AnimatedImageInner = ({
styleWhilePostmounted: styleWhilePostmounted ?? null,
hideWhilePremounted: 'display-none',
});
+ const croppedStyle = useCropStyle({
+ cropLeft,
+ cropRight,
+ cropTop,
+ cropBottom,
+ style: premountingStyle,
+ componentName: '<AnimatedImage />',
+ });
const canvasProps = getCanvasPropsFromSequenceProps(sequenceProps);
@@ -354,7 +369,7 @@ const AnimatedImageInner = ({
loopBehavior,
id,
className,
- style: premountingStyle ?? undefined,
+ style: croppedStyle ?? undefined,
requestInit,
...canvasProps,
};
diff --git a/packages/core/src/animated-image/props.ts b/packages/core/src/animated-image/props.ts
index 0f50333581..b118d579c0 100644
--- a/packages/core/src/animated-image/props.ts
+++ b/packages/core/src/animated-image/props.ts
@@ -2,6 +2,7 @@ import type {ImageFit} from '../calculate-image-fit.js';
import type {EffectsProp} from '../effects/effect-types.js';
import type {
InteractiveBaseProps,
+ InteractiveCropProps,
InteractivePremountProps,
} from '../Interactive.js';
@@ -28,6 +29,7 @@ export type RemotionAnimatedImageProps = {
} & AnimatedImageCanvasProps;
export type AnimatedImageProps = InteractiveBaseProps &
+ InteractiveCropProps &
InteractivePremountProps &
RemotionAnimatedImageProps & {
readonly effects?: EffectsProp;
diff --git a/packages/core/src/canvas-image/CanvasImage.tsx b/packages/core/src/canvas-image/CanvasImage.tsx
index 5cf1506f25..11a4e34f8f 100644
--- a/packages/core/src/canvas-image/CanvasImage.tsx
+++ b/packages/core/src/canvas-image/CanvasImage.tsx
@@ -24,6 +24,7 @@ import {
backgroundSchema,
baseSchema,
borderSchema,
+ cropSchema,
premountSchema,
transformSchema,
type InteractivitySchema,
@@ -33,6 +34,7 @@ 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 {useCropStyle} from '../use-crop-style.js';
import {useDelayRender} from '../use-delay-render.js';
import {usePremounting} from '../use-premounting.js';
import {withInteractivitySchema} from '../with-interactivity-schema.js';
@@ -40,6 +42,7 @@ import type {CanvasImageCanvasProps, CanvasImageProps} from './props.js';
export const canvasImageSchema = {
...baseSchema,
+ ...cropSchema,
...premountSchema,
fit: {
type: 'enum',
@@ -533,9 +536,14 @@ const CanvasImageInner = forwardRef<
hidden,
name,
showInTimeline,
+ cropLeft,
+ cropRight,
+ cropTop,
+ cropBottom,
stack,
controls,
_remotionInternalDocumentationLink,
+ _remotionInternalCropComponentName,
outlineRef,
...canvasProps
},
@@ -568,6 +576,14 @@ const CanvasImageInner = forwardRef<
styleWhilePostmounted: styleWhilePostmounted ?? null,
hideWhilePremounted: 'display-none',
});
+ const croppedStyle = useCropStyle({
+ cropLeft,
+ cropRight,
+ cropTop,
+ cropBottom,
+ style: premountingStyle,
+ componentName: _remotionInternalCropComponentName ?? '<CanvasImage />',
+ });
return (
<Freeze frame={freezeFrame} active={isPremountingOrPostmounting}>
@@ -603,7 +619,7 @@ const CanvasImageInner = forwardRef<
effects={effects}
controls={controls}
className={className}
- style={premountingStyle ?? undefined}
+ style={croppedStyle ?? undefined}
id={id}
onError={onError}
pauseWhenLoading={pauseWhenLoading}
diff --git a/packages/core/src/canvas-image/props.ts b/packages/core/src/canvas-image/props.ts
index a10372364a..6a9b889461 100644
--- a/packages/core/src/canvas-image/props.ts
+++ b/packages/core/src/canvas-image/props.ts
@@ -3,10 +3,12 @@ import type {ImageFit} from '../calculate-image-fit.js';
import type {EffectsProp} from '../effects/effect-types.js';
import type {
InteractiveBaseProps,
+ InteractiveCropProps,
InteractivePremountProps,
} from '../Interactive.js';
type CanvasImageSequenceProps = InteractiveBaseProps &
+ InteractiveCropProps &
InteractivePremountProps & {
/**
* @deprecated For internal use only.
@@ -38,6 +40,10 @@ export type CanvasImageProps = CanvasImageSequenceProps &
* @deprecated For internal use only.
*/
readonly _remotionInternalDocumentationLink?: string;
+ /**
+ * @deprecated For internal use only.
+ */
+ readonly _remotionInternalCropComponentName?: string;
/**
* A React ref pointing to the element that Remotion Studio should use for
* drawing the selection outline in the preview.
diff --git a/packages/core/src/effects/Solid.tsx b/packages/core/src/effects/Solid.tsx
index 5319baea1c..ec38bfa0da 100644
--- a/packages/core/src/effects/Solid.tsx
+++ b/packages/core/src/effects/Solid.tsx
@@ -9,15 +9,20 @@ import React, {
} from 'react';
import type {SequenceControls} from '../CompositionManager.js';
import {addSequenceStackTraces} from '../enable-sequence-stack-traces.js';
-import type {InteractiveBaseProps} from '../Interactive.js';
+import type {
+ InteractiveBaseProps,
+ InteractiveCropProps,
+} from '../Interactive.js';
import {
backgroundSchema,
baseSchema,
borderSchema,
+ cropSchema,
transformSchema,
type InteractivitySchema,
} from '../interactivity-schema.js';
import {Sequence} from '../Sequence.js';
+import {useCropStyle} from '../use-crop-style.js';
import {useDelayRender} from '../use-delay-render.js';
import {withInteractivitySchema} from '../with-interactivity-schema.js';
import type {EffectsProp} from './effect-types.js';
@@ -63,7 +68,9 @@ type InnerSolidProps = MandatoryProps &
OptionalProps & {
overrideId: string | null;
};
-export type SolidProps = MandatoryProps & Partial<OptionalProps>;
+export type SolidProps = MandatoryProps &
+ Partial<OptionalProps> &
+ InteractiveCropProps;
export const solidSchema = {
...baseSchema,
@@ -100,6 +107,7 @@ export const solidSchema = {
...transformSchema,
...backgroundSchema,
...borderSchema,
+ ...cropSchema,
} as const satisfies InteractivitySchema;
const SolidInner: React.FC<
@@ -263,6 +271,10 @@ const SolidOuter = forwardRef<
hidden,
showInTimeline,
pixelDensity,
+ cropLeft,
+ cropRight,
+ cropTop,
+ cropBottom,
...props
},
ref,
@@ -275,6 +287,14 @@ const SolidOuter = forwardRef<
useImperativeHandle(ref, () => {
return actualRef.current as HTMLCanvasElement;
}, []);
+ const croppedStyle = useCropStyle({
+ cropLeft,
+ cropRight,
+ cropTop,
+ cropBottom,
+ style: style ?? null,
+ componentName: '<Solid />',
+ });
return (
<Sequence
@@ -300,7 +320,7 @@ const SolidOuter = forwardRef<
height={height}
width={width}
className={className}
- style={style}
+ style={croppedStyle ?? undefined}
effects={effects}
pixelDensity={pixelDensity}
/>
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index d8a446dfcf..b750eadd19 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -202,6 +202,7 @@ export {Img, ImgProps} from './Img.js';
export {
Interactive,
type InteractiveBaseProps,
+ type InteractiveCropProps,
type InteractivePremountProps,
type InteractiveProps,
type InteractiveTransformProps,
diff --git a/packages/core/src/interactivity-schema.ts b/packages/core/src/interactivity-schema.ts
index 96ac75eb03..ef8403532a 100644
--- a/packages/core/src/interactivity-schema.ts
+++ b/packages/core/src/interactivity-schema.ts
@@ -436,7 +436,53 @@ export const sequencePremountSchema = {
...premountSchema,
} as const satisfies InteractivitySchema;
+export const cropSchema = {
+ cropLeft: {
+ type: 'number',
+ default: 0,
+ description: 'Crop left',
+ min: 0,
+ max: 1,
+ step: 0.01,
+ hiddenFromList: false,
+ keyframable: true,
+ },
+ cropRight: {
+ type: 'number',
+ default: 0,
+ description: 'Crop right',
+ min: 0,
+ max: 1,
+ step: 0.01,
+ hiddenFromList: false,
+ keyframable: true,
+ },
+ cropTop: {
+ type: 'number',
+ default: 0,
+ description: 'Crop top',
+ min: 0,
+ max: 1,
+ step: 0.01,
+ hiddenFromList: false,
+ keyframable: true,
+ },
+ cropBottom: {
+ type: 'number',
+ default: 0,
+ description: 'Crop bottom',
+ min: 0,
+ max: 1,
+ step: 0.01,
+ hiddenFromList: false,
+ keyframable: true,
+ },
+} as const satisfies InteractivitySchema;
+
+export const sequenceCropSchema = cropSchema;
+
export const sequenceStyleSchema = {
+ ...sequenceCropSchema,
...transformSchema,
...backgroundSchema,
...borderSchema,
diff --git a/packages/core/src/internals.ts b/packages/core/src/internals.ts
index 0f8168003d..e44c03f598 100644
--- a/packages/core/src/internals.ts
+++ b/packages/core/src/internals.ts
@@ -99,6 +99,7 @@ import {
hiddenField,
premountSchema,
sequencePremountSchema,
+ sequenceCropSchema,
sequenceSchema,
sequenceStyleSchema,
sequenceVisualStyleSchema,
@@ -142,6 +143,7 @@ import {
resolveCompositionsRef,
useResolvedVideoConfig,
} from './ResolveCompositionConfig.js';
+import {resolveSequenceCrop} from './sequence-crop.js';
import type {
OverrideIdToNodePaths,
OverrideToNodePathGetters,
@@ -192,6 +194,7 @@ import {
type TimelineContextValue,
} from './TimelineContext.js';
import {truthy} from './truthy.js';
+import {useCropStyle} from './use-crop-style.js';
import {
calculateScale,
CurrentScaleContext,
@@ -307,6 +310,7 @@ export const Internals = {
sequenceStyleSchema,
sequenceVisualStyleSchema,
sequencePremountSchema,
+ sequenceCropSchema,
textSchema,
transformSchema,
premountSchema,
@@ -431,6 +435,8 @@ export const Internals = {
durationInFramesField,
freezeField,
fromField,
+ resolveSequenceCrop,
+ useCropStyle,
} as const;
export type {
diff --git a/packages/core/src/sequence-crop.ts b/packages/core/src/sequence-crop.ts
new file mode 100644
index 0000000000..6d85d07f7c
--- /dev/null
+++ b/packages/core/src/sequence-crop.ts
@@ -0,0 +1,90 @@
+export type ResolvedSequenceCrop = {
+ readonly left: number;
+ readonly right: number;
+ readonly top: number;
+ readonly bottom: number;
+};
+
+type ResolvedSequenceCropWithBorderRadius = ResolvedSequenceCrop & {
+ readonly borderRadius?: string | number;
+};
+
+export type SequenceCropInput = {
+ readonly cropLeft?: number;
+ readonly cropRight?: number;
+ readonly cropTop?: number;
+ readonly cropBottom?: number;
+};
+
+const clampCrop = (value: number | undefined): number => {
+ return Math.min(1, Math.max(0, value ?? 0));
+};
+
+const resolveAxis = (
+ start: number | undefined,
+ end: number | undefined,
+): readonly [number, number] => {
+ const resolvedStart = clampCrop(start);
+ const resolvedEnd = clampCrop(end);
+
+ if (resolvedStart + resolvedEnd > 1) {
+ return [0.5, 0.5];
+ }
+
+ return [resolvedStart, resolvedEnd];
+};
+
+export const resolveSequenceCrop = ({
+ cropLeft,
+ cropRight,
+ cropTop,
+ cropBottom,
+}: SequenceCropInput): ResolvedSequenceCrop => {
+ const [left, right] = resolveAxis(cropLeft, cropRight);
+ const [top, bottom] = resolveAxis(cropTop, cropBottom);
+
+ return {left, right, top, bottom};
+};
+
+export const getSequenceCropClipPath = ({
+ left,
+ right,
+ top,
+ bottom,
+ borderRadius,
+}: ResolvedSequenceCropWithBorderRadius): string | null => {
+ if (left === 0 && right === 0 && top === 0 && bottom === 0) {
+ return null;
+ }
+
+ const serializedBorderRadius =
+ typeof borderRadius === 'number' ? `${borderRadius}px` : borderRadius;
+ const rounded = serializedBorderRadius
+ ? ` round ${serializedBorderRadius}`
+ : '';
+
+ return `inset(${top * 100}% ${right * 100}% ${bottom * 100}% ${left * 100}%${rounded})`;
+};
+
+export const validateSequenceCrop = (
+ crop: SequenceCropInput,
+ componentName = '<Sequence />',
+): void => {
+ for (const [name, value] of Object.entries(crop)) {
+ if (value === undefined) {
+ continue;
+ }
+
+ if (typeof value !== 'number' || !Number.isFinite(value)) {
+ throw new TypeError(
+ `The "${name}" prop of ${componentName} must be a finite number, but got ${String(value)}.`,
+ );
+ }
+
+ if (value < 0 || value > 1) {
+ throw new RangeError(
+ `The "${name}" prop of ${componentName} must be between 0 and 1, but got ${value}.`,
+ );
+ }
+ }
+};
diff --git a/packages/core/src/test/Img.test.tsx b/packages/core/src/test/Img.test.tsx
index 5e3f1fc5ca..f1a888a53f 100644
--- a/packages/core/src/test/Img.test.tsx
+++ b/packages/core/src/test/Img.test.tsx
@@ -417,7 +417,7 @@ test('Img with effects renders through the canvas image path', async () => {
expect(applyCalls[0].height).toBe(50);
});
-test('<Img> schema exposes src but not fit', () => {
+test('<Img> schema exposes src and crop but not fit', () => {
expect(imgSchema.src).toEqual({
type: 'asset',
default: undefined,
@@ -425,6 +425,48 @@ test('<Img> schema exposes src but not fit', () => {
keyframable: false,
});
expect(Object.keys(imgSchema)).not.toContain('fit');
+ for (const field of ['cropLeft', 'cropRight', 'cropTop', 'cropBottom']) {
+ expect(field in imgSchema).toBe(true);
+ }
+});
+
+test('<Img> applies crop props to the native image', () => {
+ const {container} = renderImg(
+ <Img
+ cropBottom={0.4}
+ cropLeft={0.1}
+ cropRight={0.2}
+ cropTop={0.3}
+ src={testImgUrl}
+ />,
+ );
+
+ const image = container.querySelector('img');
+ expect(image?.style.clipPath).toBe('inset(30% 20% 40% 10%)');
+});
+
+test('<Img> forwards crop props to the CanvasImage fallback', () => {
+ const {container} = renderImg(
+ <Img
+ cropBottom={0.4}
+ cropLeft={0.1}
+ cropRight={0.2}
+ cropTop={0.3}
+ effects={[makeEffect()]}
+ src={testImgUrl}
+ />,
+ );
+
+ const canvas = container.querySelector('canvas');
+ expect(canvas?.style.clipPath).toBe('inset(30% 20% 40% 10%)');
+});
+
+test('<Img> keeps its component name in crop errors from the fallback', () => {
+ expect(() =>
+ renderImg(<Img cropLeft={1.1} effects={[makeEffect()]} src={testImgUrl} />),
+ ).toThrow(
+ 'The "cropLeft" prop of <Img /> must be between 0 and 1, but got 1.1.',
+ );
});
test('Img throws when native image props conflict with effects', () => {
diff --git a/packages/core/src/test/canvas-image.test.tsx b/packages/core/src/test/canvas-image.test.tsx
index 0e55b084b3..4783e4c3b8 100644
--- a/packages/core/src/test/canvas-image.test.tsx
+++ b/packages/core/src/test/canvas-image.test.tsx
@@ -281,6 +281,29 @@ test('<CanvasImage> exposes non-keyframable premounting schema fields', () => {
expect(canvasImageSchema.postmountFor.keyframable).toBe(false);
});
+test('<CanvasImage> applies crop props to the canvas', async () => {
+ const {container} = render(
+ wrapCanvasImage(
+ <CanvasImage
+ src="test.png"
+ width={120}
+ height={80}
+ cropLeft={0.1}
+ cropRight={0.2}
+ cropTop={0.3}
+ cropBottom={0.4}
+ />,
+ ),
+ );
+
+ const canvas = container.querySelector('canvas');
+ expect(canvas?.style.clipPath).toBe('inset(30% 20% 40% 10%)');
+
+ await waitFor(() => {
+ expect(getDelayRenderState().remotion_renderReady).toBe(true);
+ });
+});
+
test('<CanvasImage> hides the canvas while premounted and postmounted', async () => {
const premounted = render(
wrapCanvasImage(
diff --git a/packages/core/src/test/find-props-to-delete.test.ts b/packages/core/src/test/find-props-to-delete.test.ts
index 8d2d497ea2..8a30ae791f 100644
--- a/packages/core/src/test/find-props-to-delete.test.ts
+++ b/packages/core/src/test/find-props-to-delete.test.ts
@@ -34,6 +34,10 @@ test('find right values to delete when upgrading a discriminated union', () => {
value: 'none',
}),
).toEqual([
+ 'cropLeft',
+ 'cropRight',
+ 'cropTop',
+ 'cropBottom',
'style.transformOrigin',
'style.translate',
'style.scale',
diff --git a/packages/core/src/test/html-in-canvas.test.tsx b/packages/core/src/test/html-in-canvas.test.tsx
index 30f1488a55..eb90278c98 100644
--- a/packages/core/src/test/html-in-canvas.test.tsx
+++ b/packages/core/src/test/html-in-canvas.test.tsx
@@ -4,7 +4,7 @@ import React, {useCallback, useMemo} from 'react';
import type {TSequence} from '../CompositionManager.js';
import type {DelayRenderScope} from '../delay-render.js';
import type {HtmlInCanvasOnPaintParams} from '../HtmlInCanvas.js';
-import {HtmlInCanvas} from '../HtmlInCanvas.js';
+import {HtmlInCanvas, htmlInCanvasSchema} from '../HtmlInCanvas.js';
import {Internals} from '../internals.js';
import type {SequenceManagerContext} from '../SequenceManager.js';
import {
@@ -291,6 +291,34 @@ test('<HtmlInCanvas> registers its canvas for outline selection', async () => {
expect(registeredSequences[0]?.refForOutline?.current).toBe(canvas);
});
+test('<HtmlInCanvas> applies crop props to its canvas', () => {
+ const {container} = render(
+ <SequenceTestWrapper onRegisterSequence={() => undefined}>
+ <HtmlInCanvas
+ width={120}
+ height={80}
+ cropLeft={0.1}
+ cropRight={0.2}
+ cropTop={0.3}
+ cropBottom={0.4}
+ >
+ <div>Test</div>
+ </HtmlInCanvas>
+ </SequenceTestWrapper>,
+ );
+
+ expect(container.querySelector('canvas')?.style.clipPath).toBe(
+ 'inset(30% 20% 40% 10%)',
+ );
+});
+
+test('<HtmlInCanvas> exposes crop controls', () => {
+ expect(htmlInCanvasSchema.cropLeft.keyframable).toBe(true);
+ expect(htmlInCanvasSchema.cropRight.keyframable).toBe(true);
+ expect(htmlInCanvasSchema.cropTop.keyframable).toBe(true);
+ expect(htmlInCanvasSchema.cropBottom.keyframable).toBe(true);
+});
+
test('<HtmlInCanvas> keeps refs current when the canvas remounts', async () => {
const registeredSequences: TSequence[] = [];
const canvasRef = React.createRef<HTMLCanvasElement>();
diff --git a/packages/core/src/test/sequence-crop.test.tsx b/packages/core/src/test/sequence-crop.test.tsx
new file mode 100644
index 0000000000..fe9cbd9dca
--- /dev/null
+++ b/packages/core/src/test/sequence-crop.test.tsx
@@ -0,0 +1,96 @@
+import {afterEach, expect, test} from 'bun:test';
+import {cleanup, render} from '@testing-library/react';
+import {resolveSequenceCrop} from '../sequence-crop.js';
+import {Sequence} from '../Sequence.js';
+import {WrapSequenceContext} from './wrap-sequence-context.js';
+
+afterEach(() => {
+ cleanup();
+});
+
+test('applies Sequence crop values as an inset clip path', () => {
+ const {container} = render(
+ <WrapSequenceContext>
+ <Sequence cropLeft={0.1} cropRight={0.2} cropTop={0.3} cropBottom={0.4}>
+ Content
+ </Sequence>
+ </WrapSequenceContext>,
+ );
+
+ const sequence = container.firstElementChild as HTMLDivElement;
+ expect(sequence.style.clipPath).toBe('inset(30% 20% 40% 10%)');
+});
+
+test('preserves a numeric border radius on the cropped rectangle', () => {
+ const {container} = render(
+ <WrapSequenceContext>
+ <Sequence cropLeft={0.1} style={{borderRadius: 24}}>
+ Content
+ </Sequence>
+ </WrapSequenceContext>,
+ );
+
+ const sequence = container.firstElementChild as HTMLDivElement;
+ expect(sequence.style.clipPath).toBe('inset(0% 0% 0% 10% round 24px)');
+});
+
+test('preserves a string border radius on the cropped rectangle', () => {
+ const {container} = render(
+ <WrapSequenceContext>
+ <Sequence cropTop={0.2} style={{borderRadius: '20% / 10%'}}>
+ Content
+ </Sequence>
+ </WrapSequenceContext>,
+ );
+
+ const sequence = container.firstElementChild as HTMLDivElement;
+ expect(sequence.style.clipPath).toBe('inset(20% 0% 0% 0% round 20% / 10%)');
+});
+
+test('does not override a custom clip path when no crop is applied', () => {
+ const {container} = render(
+ <WrapSequenceContext>
+ <Sequence style={{clipPath: 'circle(50%)'}}>Content</Sequence>
+ </WrapSequenceContext>,
+ );
+
+ const sequence = container.firstElementChild as HTMLDivElement;
+ expect(sequence.style.clipPath).toBe('circle(50%)');
+});
+
+test('clashing crops meet in the middle', () => {
+ expect(
+ resolveSequenceCrop({
+ cropLeft: 0.6,
+ cropRight: 0.6,
+ cropTop: 0.8,
+ cropBottom: 0.4,
+ }),
+ ).toEqual({left: 0.5, right: 0.5, top: 0.5, bottom: 0.5});
+});
+
+test('rejects crops outside the 0 to 1 range', () => {
+ expect(() =>
+ render(
+ <WrapSequenceContext>
+ <Sequence cropLeft={1.1}>Content</Sequence>
+ </WrapSequenceContext>,
+ ),
+ ).toThrow(
+ 'The "cropLeft" prop of <Sequence /> must be between 0 and 1, but got 1.1.',
+ );
+});
+
+test('rejects crop props in layout none mode', () => {
+ expect(() =>
+ render(
+ <WrapSequenceContext>
+ <Sequence layout="none" cropLeft={0.1}>
+ Content
+ </Sequence>
+ </WrapSequenceContext>,
+ ),
+ ).toThrow(
+ 'The cropLeft, cropRight, cropTop and cropBottom props of <Sequence /> are only supported with layout="absolute-fill".',
+ );
+});
diff --git a/packages/core/src/test/sequence-register-once.test.tsx b/packages/core/src/test/sequence-register-once.test.tsx
index b60d3deee1..5dae8efe26 100644
--- a/packages/core/src/test/sequence-register-once.test.tsx
+++ b/packages/core/src/test/sequence-register-once.test.tsx
@@ -679,6 +679,24 @@ test('AnimatedImage exposes non-keyframable premounting schema fields', () => {
expect(animatedImageSchema.postmountFor.keyframable).toBe(false);
});
+test('AnimatedImage applies crop props to its canvas', () => {
+ const {container} = render(
+ <SequenceTestWrapper onRegisterSequence={() => undefined}>
+ <AnimatedImage
+ cropBottom={0.4}
+ cropLeft={0.1}
+ cropRight={0.2}
+ cropTop={0.3}
+ onError={() => undefined}
+ src="test.gif"
+ />
+ </SequenceTestWrapper>,
+ );
+
+ const canvas = container.querySelector('canvas');
+ expect(canvas?.style.clipPath).toBe('inset(30% 20% 40% 10%)');
+});
+
test('AnimatedImage hides the canvas while premounted and postmounted', () => {
const premounted = render(
<SequenceTestWrapper currentFrame={0} onRegisterSequence={() => undefined}>
diff --git a/packages/core/src/test/solid.test.tsx b/packages/core/src/test/solid.test.tsx
index 3064aba36e..569a7c14e1 100644
--- a/packages/core/src/test/solid.test.tsx
+++ b/packages/core/src/test/solid.test.tsx
@@ -1,6 +1,6 @@
import {afterEach, expect, test} from 'bun:test';
import {cleanup, render} from '@testing-library/react';
-import {Solid} from '../effects/Solid.js';
+import {Solid, solidSchema} from '../effects/Solid.js';
import {WrapSequenceContext} from './wrap-sequence-context.js';
// happy-dom doesn't implement canvas; install a no-op stub so the chain
@@ -68,6 +68,33 @@ test('<Solid> forwards className and style', () => {
expect(canvas?.style.opacity).toBe('0.5');
});
+test('<Solid> applies crop props to the canvas', () => {
+ const {container} = render(
+ <WrapSequenceContext>
+ <Solid
+ color="blue"
+ width={100}
+ height={100}
+ cropLeft={0.1}
+ cropRight={0.2}
+ cropTop={0.3}
+ cropBottom={0.4}
+ />
+ </WrapSequenceContext>,
+ );
+
+ expect(container.querySelector('canvas')?.style.clipPath).toBe(
+ 'inset(30% 20% 40% 10%)',
+ );
+});
+
+test('<Solid> exposes crop controls', () => {
+ expect(solidSchema.cropLeft.keyframable).toBe(true);
+ expect(solidSchema.cropRight.keyframable).toBe(true);
+ expect(solidSchema.cropTop.keyframable).toBe(true);
+ expect(solidSchema.cropBottom.keyframable).toBe(true);
+});
+
test('<Solid> renders without a color', () => {
const {container} = render(
<WrapSequenceContext>
diff --git a/packages/core/src/test/use-crop-style.test.tsx b/packages/core/src/test/use-crop-style.test.tsx
new file mode 100644
index 0000000000..d6bd06a06b
--- /dev/null
+++ b/packages/core/src/test/use-crop-style.test.tsx
@@ -0,0 +1,59 @@
+import {afterEach, expect, test} from 'bun:test';
+import {cleanup, renderHook} from '@testing-library/react';
+import {useCropStyle} from '../use-crop-style.js';
+
+afterEach(() => {
+ cleanup();
+});
+
+test('preserves the style object when no crop is applied', () => {
+ const style = {clipPath: 'circle(50%)'};
+ const {result} = renderHook(() =>
+ useCropStyle({
+ style,
+ componentName: '<Test />',
+ }),
+ );
+
+ expect(result.current).toBe(style);
+});
+
+test('memoizes the cropped style object', () => {
+ const style = {opacity: 0.5};
+ const {result, rerender} = renderHook(
+ ({cropLeft}: {readonly cropLeft: number}) =>
+ useCropStyle({
+ cropLeft,
+ style,
+ componentName: '<Test />',
+ }),
+ {initialProps: {cropLeft: 0.25}},
+ );
+ const firstStyle = result.current;
+
+ expect(firstStyle).toEqual({opacity: 0.5, clipPath: 'inset(0% 0% 0% 25%)'});
+ rerender({cropLeft: 0.25});
+ expect(result.current).toBe(firstStyle);
+
+ rerender({cropLeft: 0.5});
+ expect(result.current).toEqual({
+ opacity: 0.5,
+ clipPath: 'inset(0% 0% 0% 50%)',
+ });
+ expect(result.current).not.toBe(firstStyle);
+});
+
+test('preserves the inline border radius on the cropped rectangle', () => {
+ const {result} = renderHook(() =>
+ useCropStyle({
+ cropRight: 0.25,
+ style: {borderRadius: '12px 24px'},
+ componentName: '<Test />',
+ }),
+ );
+
+ expect(result.current).toEqual({
+ borderRadius: '12px 24px',
+ clipPath: 'inset(0% 25% 0% 0% round 12px 24px)',
+ });
+});
diff --git a/packages/core/src/test/with-interactivity-schema-helpers.test.ts b/packages/core/src/test/with-interactivity-schema-helpers.test.ts
index 6fa35cca55..2e15b91114 100644
--- a/packages/core/src/test/with-interactivity-schema-helpers.test.ts
+++ b/packages/core/src/test/with-interactivity-schema-helpers.test.ts
@@ -15,9 +15,11 @@ import {
backgroundSchema,
baseSchema,
borderSchema,
+ cropSchema,
extendSchemaWithSequenceName,
premountSchema,
sequencePremountSchema,
+ sequenceCropSchema,
sequenceSchema,
sequenceSchemaWithoutFrom,
sequenceStyleSchema,
@@ -37,6 +39,7 @@ import {
test('sequenceStyleSchema contains visual style and premount fields', () => {
expect(Object.keys(sequenceStyleSchema).sort()).toEqual(
[
+ ...Object.keys(sequenceCropSchema),
...Object.keys(transformSchema),
...Object.keys(backgroundSchema),
...Object.keys(borderSchema),
@@ -69,6 +72,37 @@ test('premount fields are not keyframable', () => {
expect(premountSchema.postmountFor.keyframable).toBe(false);
});
+test('Sequence crop fields are keyframable ratios', () => {
+ for (const field of Object.values(sequenceCropSchema)) {
+ expect(field).toMatchObject({
+ type: 'number',
+ default: 0,
+ min: 0,
+ max: 1,
+ keyframable: true,
+ });
+ }
+});
+
+test('cropSchema is reusable and supported components opt into it', () => {
+ expect(Interactive.cropSchema).toBe(cropSchema);
+ expect(sequenceCropSchema).toBe(cropSchema);
+
+ for (const key of Object.keys(cropSchema)) {
+ for (const schema of [
+ animatedImageSchema,
+ canvasImageSchema,
+ htmlInCanvasSchema,
+ imgSchema,
+ solidSchema,
+ ]) {
+ expect(key in schema).toBe(true);
+ }
+ }
+
+ expect('cropLeft' in baseSchema).toBe(false);
+});
+
test('baseSchema exposes common timeline fields', () => {
expect(Object.keys(baseSchema).sort()).toEqual(
[
@@ -142,6 +176,10 @@ test('getFlatSchema(sequenceSchema) exposes every variant key', () => {
const flat = getFlatSchemaWithAllKeys(sequenceSchema);
expect(Object.keys(flat).sort()).toEqual(
[
+ 'cropBottom',
+ 'cropLeft',
+ 'cropRight',
+ 'cropTop',
'hidden',
'name',
'showInTimeline',
@@ -459,6 +497,10 @@ test('selectActiveKeys exposes style.* keys when layout=absolute-fill', () => {
};
expect(selectActiveKeys(sequenceSchema, values).sort()).toEqual(
[
+ 'cropBottom',
+ 'cropLeft',
+ 'cropRight',
+ 'cropTop',
'hidden',
'layout',
'durationInFrames',
diff --git a/packages/core/src/use-crop-style.ts b/packages/core/src/use-crop-style.ts
new file mode 100644
index 0000000000..b1b768b00c
--- /dev/null
+++ b/packages/core/src/use-crop-style.ts
@@ -0,0 +1,38 @@
+import {useMemo} from 'react';
+import type React from 'react';
+import {
+ getSequenceCropClipPath,
+ resolveSequenceCrop,
+ type SequenceCropInput,
+ validateSequenceCrop,
+} from './sequence-crop.js';
+
+export const useCropStyle = ({
+ cropLeft,
+ cropRight,
+ cropTop,
+ cropBottom,
+ style,
+ componentName,
+}: SequenceCropInput & {
+ readonly style: React.CSSProperties | null;
+ readonly componentName: string;
+}): React.CSSProperties | null => {
+ validateSequenceCrop(
+ {cropLeft, cropRight, cropTop, cropBottom},
+ componentName,
+ );
+
+ return useMemo(() => {
+ const cropClipPath = getSequenceCropClipPath({
+ ...resolveSequenceCrop({cropLeft, cropRight, cropTop, cropBottom}),
+ borderRadius: style?.borderRadius,
+ });
+
+ if (cropClipPath === null) {
+ return style;
+ }
+
+ return {...style, clipPath: cropClipPath};
+ }, [cropBottom, cropLeft, cropRight, cropTop, style]);
+};
diff --git a/packages/docs/docs/animatedimage.mdx b/packages/docs/docs/animatedimage.mdx
index 057f7e5e40..1695a17a5f 100644
--- a/packages/docs/docs/animatedimage.mdx
+++ b/packages/docs/docs/animatedimage.mdx
@@ -72,6 +72,22 @@ Must be one of these values:
Allows to pass in custom CSS styles. You may not pass `width` and `height`, instead use the props `width` and `height` to set the size of the image.
+### `cropLeft?`<AvailableFrom v="4.0.500" />
+
+Crops the canvas from the left by a ratio between `0` and `1`. See [`cropLeft`](/docs/sequence#cropleft).
+
+### `cropRight?`<AvailableFrom v="4.0.500" />
+
+Crops the canvas from the right by a ratio between `0` and `1`. See [`cropRight`](/docs/sequence#cropright).
+
+### `cropTop?`<AvailableFrom v="4.0.500" />
+
+Crops the canvas from the top by a ratio between `0` and `1`. See [`cropTop`](/docs/sequence#croptop).
+
+### `cropBottom?`<AvailableFrom v="4.0.500" />
+
+Crops the canvas from the bottom by a ratio between `0` and `1`. See [`cropBottom`](/docs/sequence#cropbottom).
+
### `premountFor?`<AvailableFrom v="4.0.497" />
Mounts the canvas for the specified number of frames before its `from` frame. The canvas carries `display: none` and is frozen at its first frame while premounted.
diff --git a/packages/docs/docs/canvasimage.mdx b/packages/docs/docs/canvasimage.mdx
index c4c6c07bbd..ba648fe61e 100644
--- a/packages/docs/docs/canvasimage.mdx
+++ b/packages/docs/docs/canvasimage.mdx
@@ -67,6 +67,22 @@ The HTML `id` attribute to apply to the `<canvas>` element.
Inline styles to apply to the `<canvas>` element.
+### `cropLeft?`<AvailableFrom v="4.0.500" />
+
+Crops the canvas from the left by a ratio between `0` and `1`. See [`cropLeft`](/docs/sequence#cropleft).
+
+### `cropRight?`<AvailableFrom v="4.0.500" />
+
+Crops the canvas from the right by a ratio between `0` and `1`. See [`cropRight`](/docs/sequence#cropright).
+
+### `cropTop?`<AvailableFrom v="4.0.500" />
+
+Crops the canvas from the top by a ratio between `0` and `1`. See [`cropTop`](/docs/sequence#croptop).
+
+### `cropBottom?`<AvailableFrom v="4.0.500" />
+
+Crops the canvas from the bottom by a ratio between `0` and `1`. See [`cropBottom`](/docs/sequence#cropbottom).
+
### `premountFor?`<AvailableFrom v="4.0.495" />
Mounts the canvas for the specified number of frames before its `from` frame. The canvas carries `display: none` and is frozen at its first frame while premounted.
diff --git a/packages/docs/docs/gif/gif.mdx b/packages/docs/docs/gif/gif.mdx
index a1ffd3bb5d..63b83a69ec 100644
--- a/packages/docs/docs/gif/gif.mdx
+++ b/packages/docs/docs/gif/gif.mdx
@@ -91,6 +91,22 @@ Callback that gets called once the GIF has loaded and finished processing. As it
Allows to pass in custom CSS styles. You may not pass `width` and `height`, instead use the props `width` and `height` to set the size of the GIF.
+### `cropLeft?`<AvailableFrom v="4.0.500" />
+
+Crops the canvas from the left by a ratio between 0 and 1. See [`cropLeft`](/docs/sequence#cropleft) on `<Sequence>`.
+
+### `cropRight?`<AvailableFrom v="4.0.500" />
+
+Crops the canvas from the right by a ratio between 0 and 1. See [`cropRight`](/docs/sequence#cropright) on `<Sequence>`.
+
+### `cropTop?`<AvailableFrom v="4.0.500" />
+
+Crops the canvas from the top by a ratio between 0 and 1. See [`cropTop`](/docs/sequence#croptop) on `<Sequence>`.
+
+### `cropBottom?`<AvailableFrom v="4.0.500" />
+
+Crops the canvas from the bottom by a ratio between 0 and 1. See [`cropBottom`](/docs/sequence#cropbottom) on `<Sequence>`.
+
### `premountFor?`<AvailableFrom v="4.0.497" />
Mounts the canvas for the specified number of frames before its `from` frame. The canvas carries `display: none` and is frozen at its first frame while premounted.
diff --git a/packages/docs/docs/img.mdx b/packages/docs/docs/img.mdx
index 14e76753c7..4a67adbd50 100644
--- a/packages/docs/docs/img.mdx
+++ b/packages/docs/docs/img.mdx
@@ -67,6 +67,22 @@ The unsupported props include `ref`, `srcSet`, `sizes`, `loading`, `decoding`, `
Canvas-compatible props such as `aria-*`, `data-*`, `role`, `title`, `tabIndex` and pointer or mouse event handlers are forwarded to the underlying `<canvas>`.
When [`effects`](#effects) is a non-empty array, `style.objectFit` controls how the image is drawn into the canvas. Supported values are `"fill"`, `"contain"` and `"cover"`.
+### `cropLeft?`<AvailableFrom v="4.0.500" />
+
+Crops the image from the left by a ratio between `0` and `1`. See [`cropLeft`](/docs/sequence#cropleft).
+
+### `cropRight?`<AvailableFrom v="4.0.500" />
+
+Crops the image from the right by a ratio between `0` and `1`. See [`cropRight`](/docs/sequence#cropright).
+
+### `cropTop?`<AvailableFrom v="4.0.500" />
+
+Crops the image from the top by a ratio between `0` and `1`. See [`cropTop`](/docs/sequence#croptop).
+
+### `cropBottom?`<AvailableFrom v="4.0.500" />
+
+Crops the image from the bottom by a ratio between `0` and `1`. See [`cropBottom`](/docs/sequence#cropbottom).
+
### `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/docs/docs/interactive-with-schema.mdx b/packages/docs/docs/interactive-with-schema.mdx
index 08cb3a85e4..31b9a8a7ae 100644
--- a/packages/docs/docs/interactive-with-schema.mdx
+++ b/packages/docs/docs/interactive-with-schema.mdx
@@ -129,7 +129,7 @@ Forward it to the `<Sequence>` that registers the component in the timeline.
An [`InteractivitySchema`](/docs/interactivity-schema) that describes which props are editable in Remotion Studio.
-Use [`Interactive.baseSchema`](/docs/interactive#interactivebaseschema) for Sequence-like timeline props. Use [`Interactive.transformSchema`](/docs/interactive#interactivetransformschema) if the component accepts a `style` prop and should expose transform controls.
+Use [`Interactive.baseSchema`](/docs/interactive#interactivebaseschema) for Sequence-like timeline props. Use [`Interactive.transformSchema`](/docs/interactive#interactivetransformschema) if the component accepts a `style` prop and should expose transform controls. Use [`Interactive.cropSchema`](/docs/interactive#interactivecropschema) with `InteractiveCropProps` to opt the component into crop controls.
For reliable source updates, follow [Interactivity best practices](/docs/studio/interactivity-best-practices): Keep editable values inline, use hardcoded `interpolate()` keyframe arrays, use `translate`, `scale`, `rotate` and `opacity` directly, and avoid animated layout props or `transform` strings.
### `componentIdentity`
diff --git a/packages/docs/docs/interactive.mdx b/packages/docs/docs/interactive.mdx
index c35adf2dea..793620c9b2 100644
--- a/packages/docs/docs/interactive.mdx
+++ b/packages/docs/docs/interactive.mdx
@@ -99,6 +99,14 @@ Controls for transform-related style props:
Use it for components that accept a `style` prop and apply it to the rendered element.
Keep these values inline in JSX if the Studio should edit or keyframe them.
+### `Interactive.cropSchema`<AvailableFrom v="4.0.500" />
+
+Controls for cropping an element from each edge:
+
+[`cropLeft`](/docs/sequence#cropleft), [`cropRight`](/docs/sequence#cropright), [`cropTop`](/docs/sequence#croptop) and [`cropBottom`](/docs/sequence#cropbottom).
+
+Spread this schema into a custom component's schema to opt it into crop controls. The component must apply the crop props to its rendered element or forward them to an absolute-fill [`<Sequence>`](/docs/sequence).
+
### `Interactive.textSchema`<AvailableFrom v="4.0.481" />
Controls for text-related style props:
@@ -151,7 +159,7 @@ Use it for components that forward these props to a `<Sequence>`.
The schema used by [`<Sequence>`](/docs/sequence).
-It includes `Interactive.baseSchema` and a `layout` field. When `layout` is `"absolute-fill"`, the active fields include `Interactive.transformSchema`, `Interactive.backgroundSchema`, `Interactive.borderSchema` and `Interactive.premountSchema`.
+It includes `Interactive.baseSchema` and a `layout` field. When `layout` is `"absolute-fill"`, the active fields include [`cropLeft`](/docs/sequence#cropleft), [`cropRight`](/docs/sequence#cropright), [`cropTop`](/docs/sequence#croptop), [`cropBottom`](/docs/sequence#cropbottom), `Interactive.transformSchema`, `Interactive.backgroundSchema`, `Interactive.borderSchema` and `Interactive.premountSchema`.
### `Interactive.withSchema()`<AvailableFrom v="4.0.479" />
@@ -169,6 +177,10 @@ The prop type matching `Interactive.baseSchema`.
The prop type matching `Interactive.transformSchema`.
+### `InteractiveCropProps`<AvailableFrom v="4.0.500" />
+
+The prop type matching `Interactive.cropSchema`.
+
### `InteractivePremountProps`<AvailableFrom v="4.0.479" />
The prop type matching `Interactive.premountSchema`.
diff --git a/packages/docs/docs/interactivity-schema.mdx b/packages/docs/docs/interactivity-schema.mdx
index 4f62d123ca..d47ad73040 100644
--- a/packages/docs/docs/interactivity-schema.mdx
+++ b/packages/docs/docs/interactivity-schema.mdx
@@ -43,6 +43,12 @@ Timeline props inherited from [`<Sequence>`](/docs/sequence): [`durationInFrames
Transform-related style props: `style.transformOrigin`, `style.translate`, `style.scale`, `style.rotate` and `style.opacity`.
+### `Interactive.cropSchema`<AvailableFrom v="4.0.500" />
+
+Crop props inherited from an absolute-fill [`<Sequence>`](/docs/sequence): [`cropLeft`](/docs/sequence#cropleft), [`cropRight`](/docs/sequence#cropright), [`cropTop`](/docs/sequence#croptop) and [`cropBottom`](/docs/sequence#cropbottom).
+
+Use this fragment to opt a custom component into crop controls. The component must apply the crop props to its rendered element or forward them to an absolute-fill `<Sequence>`.
+
### `Interactive.textSchema`<AvailableFrom v="4.0.481" />
Text-related style props: `style.color`, `style.fontFamily`, `style.fontSize`, `style.lineHeight`, `style.fontWeight`, `style.fontStyle`, `style.textAlign` and `style.letterSpacing`.
diff --git a/packages/docs/docs/remotion/html-in-canvas.mdx b/packages/docs/docs/remotion/html-in-canvas.mdx
index f71b817cfc..5fb5e6d012 100644
--- a/packages/docs/docs/remotion/html-in-canvas.mdx
+++ b/packages/docs/docs/remotion/html-in-canvas.mdx
@@ -145,6 +145,22 @@ Runs once before the first paint. Use it to create GPU contexts or other resourc
The argument object matches [`onPaint`](#onpaint) (`canvas`, `element`, `elementImage`). The `elementImage` passed here is only for initialization β€” capture again inside [`onPaint`](#onpaint) for each frame.
+### `cropLeft?`<AvailableFrom v="4.0.500" />
+
+Crops the canvas from the left by a ratio between 0 and 1. See [`cropLeft`](/docs/sequence#cropleft) on `<Sequence>`.
+
+### `cropRight?`<AvailableFrom v="4.0.500" />
+
+Crops the canvas from the right by a ratio between 0 and 1. See [`cropRight`](/docs/sequence#cropright) on `<Sequence>`.
+
+### `cropTop?`<AvailableFrom v="4.0.500" />
+
+Crops the canvas from the top by a ratio between 0 and 1. See [`cropTop`](/docs/sequence#croptop) on `<Sequence>`.
+
+### `cropBottom?`<AvailableFrom v="4.0.500" />
+
+Crops the canvas from the bottom by a ratio between 0 and 1. See [`cropBottom`](/docs/sequence#cropbottom) on `<Sequence>`.
+
### `durationInFrames?`
Inherited from [`<Sequence>`](/docs/sequence#durationinframes).
diff --git a/packages/docs/docs/rive/remotionrivecanvas.mdx b/packages/docs/docs/rive/remotionrivecanvas.mdx
index b02a70ffb8..f1f529db19 100644
--- a/packages/docs/docs/rive/remotionrivecanvas.mdx
+++ b/packages/docs/docs/rive/remotionrivecanvas.mdx
@@ -125,6 +125,22 @@ A class name to apply to the underlying `<canvas>` element.
Inline styles to apply to the underlying `<canvas>` element.
+### `cropLeft?`<AvailableFrom v="4.0.500" />
+
+Crops the canvas from the left by a ratio between `0` and `1`. See [`cropLeft`](/docs/sequence#cropleft).
+
+### `cropRight?`<AvailableFrom v="4.0.500" />
+
+Crops the canvas from the right by a ratio between `0` and `1`. See [`cropRight`](/docs/sequence#cropright).
+
+### `cropTop?`<AvailableFrom v="4.0.500" />
+
+Crops the canvas from the top by a ratio between `0` and `1`. See [`cropTop`](/docs/sequence#croptop).
+
+### `cropBottom?`<AvailableFrom v="4.0.500" />
+
+Crops the canvas from the bottom by a ratio between `0` and `1`. See [`cropBottom`](/docs/sequence#cropbottom).
+
## Inherited props<AvailableFrom v="4.0.464" />
`<RemotionRiveCanvas>` inherits [`from`](/docs/sequence#from), [`durationInFrames`](/docs/sequence#durationinframes), [`trimBefore`](/docs/sequence#trimbefore)<AvailableFrom v="4.0.482" inline />, [`name`](/docs/sequence#name), [`showInTimeline`](/docs/sequence#showintimeline) and [`hidden`](/docs/sequence#hidden) from [`<Sequence>`](/docs/sequence).
diff --git a/packages/docs/docs/sequence.mdx b/packages/docs/docs/sequence.mdx
index 3e987decb9..8d0f33c183 100644
--- a/packages/docs/docs/sequence.mdx
+++ b/packages/docs/docs/sequence.mdx
@@ -255,6 +255,49 @@ You can give your sequence a name and it will be shown as the label of the seque
Either `"absolute-fill"` _(default)_ or `"none"`. By default, your sequences will be absolutely positioned, so they will overlay each other. If you would like to opt out of it and handle layouting yourself, pass `layout="none"`. Available since v1.4.
+### `cropLeft?`<AvailableFrom v="4.0.500" />
+
+Crops the Sequence from the left edge without changing its size or transform origin. The value is a ratio between `0` and `1`: `0` does not crop the edge, while `1` crops the full width.
+
+### `cropRight?`<AvailableFrom v="4.0.500" />
+
+Like [`cropLeft`](#cropleft), but crops from the right edge.
+
+If `cropLeft` and `cropRight` overlap, both edges meet in the center.
+
+### `cropTop?`<AvailableFrom v="4.0.500" />
+
+Like [`cropLeft`](#cropleft), but crops the height from the top edge.
+
+### `cropBottom?`<AvailableFrom v="4.0.500" />
+
+Like [`cropTop`](#croptop), but crops from the bottom edge.
+
+If `cropTop` and `cropBottom` overlap, both edges meet in the center.
+
+All four crop props are only supported with `layout="absolute-fill"` and can be animated:
+
+:::note
+If an inline [`style.borderRadius`](https://developer.mozilla.org/en-US/docs/Web/CSS/border-radius) is set, the cropped rectangle uses the same corner radius. A border radius applied through a CSS class is not inherited by the crop.
+:::
+
+```tsx twoslash title="MyVideo.tsx"
+import {interpolate, Sequence, useCurrentFrame} from 'remotion';
+
+export const MyVideo = () => {
+ const frame = useCurrentFrame();
+ const cropLeft = interpolate(frame, [0, 30], [0, 0.5], {
+ extrapolateRight: 'clamp',
+ });
+
+ return (
+ <Sequence cropLeft={cropLeft}>
+ <div>Revealed from the left</div>
+ </Sequence>
+ );
+};
+```
+
### `outlineRef?`<AvailableFrom v="4.0.479" />
A React ref pointing to the element that the Remotion Studio should use for drawing the selection outline in the preview.
diff --git a/packages/docs/docs/solid.mdx b/packages/docs/docs/solid.mdx
index a3b9d96970..14e807cb95 100644
--- a/packages/docs/docs/solid.mdx
+++ b/packages/docs/docs/solid.mdx
@@ -70,6 +70,22 @@ A class name to apply to the `<canvas>` element.
Inline styles to apply to the `<canvas>` element.
+### `cropLeft?`<AvailableFrom v="4.0.500" />
+
+Crops the canvas from the left by a ratio between 0 and 1. See [`cropLeft`](/docs/sequence#cropleft) on `<Sequence>`.
+
+### `cropRight?`<AvailableFrom v="4.0.500" />
+
+Crops the canvas from the right by a ratio between 0 and 1. See [`cropRight`](/docs/sequence#cropright) on `<Sequence>`.
+
+### `cropTop?`<AvailableFrom v="4.0.500" />
+
+Crops the canvas from the top by a ratio between 0 and 1. See [`cropTop`](/docs/sequence#croptop) on `<Sequence>`.
+
+### `cropBottom?`<AvailableFrom v="4.0.500" />
+
+Crops the canvas from the bottom by a ratio between 0 and 1. See [`cropBottom`](/docs/sequence#cropbottom) on `<Sequence>`.
+
### Inherited props
`<Solid>` inherits [`from`](/docs/sequence#from), [`durationInFrames`](/docs/sequence#durationinframes), [`trimBefore`](/docs/sequence#trimbefore)<AvailableFrom v="4.0.482" inline />, [`name`](/docs/sequence#name), [`showInTimeline`](/docs/sequence#showintimeline) and [`hidden`](/docs/sequence#hidden) from [`<Sequence>`](/docs/sequence).
diff --git a/packages/docs/docs/studio/make-component-interactive.mdx b/packages/docs/docs/studio/make-component-interactive.mdx
index ba848e8821..99734d4b96 100644
--- a/packages/docs/docs/studio/make-component-interactive.mdx
+++ b/packages/docs/docs/studio/make-component-interactive.mdx
@@ -19,6 +19,8 @@ Use [`Interactive.baseSchema`](/docs/interactive#interactivebaseschema) for prop
Use [`Interactive.transformSchema`](/docs/interactive#interactivetransformschema) if your component accepts a `style` prop and applies it to the rendered element.
+Use [`Interactive.cropSchema`](/docs/interactive#interactivecropschema) and `InteractiveCropProps` to opt a component into the crop controls inherited from an absolute-fill [`<Sequence>`](/docs/sequence).
+
```tsx twoslash title="Badge.tsx"
import type React from 'react';
import {
@@ -288,6 +290,10 @@ Use it when the component renders a `<Sequence>` internally.
Use it when the component accepts a `style` prop and applies it to the rendered element.
+### `Interactive.cropSchema`<AvailableFrom v="4.0.500" />
+
+Use it with `InteractiveCropProps` when the component applies crop props to its rendered element or forwards them to an absolute-fill [`<Sequence>`](/docs/sequence).
+
### `Interactive.premountSchema`
Use it when the component forwards `premountFor` and `postmountFor` to a `<Sequence>`.
diff --git a/packages/example/src/Root.tsx b/packages/example/src/Root.tsx
index 0fbda13ed6..7dec12de85 100644
--- a/packages/example/src/Root.tsx
+++ b/packages/example/src/Root.tsx
@@ -125,6 +125,7 @@ import {ScalePath} from './ScalePath';
import {SchemaTest, schemaTestSchema} from './SchemaTest';
import {Scripts} from './Scripts';
import {WidthHeightSequences} from './Sequence/WidthHeightSequences';
+import {SequenceCropTest} from './SequenceCropTest';
import CircleTest from './Shapes/CircleTest';
import EllipseTest from './Shapes/EllipseTest';
import RectTest from './Shapes/RectTest';
@@ -2671,6 +2672,14 @@ export const Index: React.FC = () => {
fps={30}
durationInFrames={120}
/>
+ <Composition
+ id="sequence-crop-controls"
+ component={SequenceCropTest}
+ width={1080}
+ height={1080}
+ fps={30}
+ durationInFrames={120}
+ />
<Composition
id="sfx"
component={SfxExample}
diff --git a/packages/example/src/SequenceCropTest.tsx b/packages/example/src/SequenceCropTest.tsx
new file mode 100644
index 0000000000..144b7e6f08
--- /dev/null
+++ b/packages/example/src/SequenceCropTest.tsx
@@ -0,0 +1,165 @@
+import React from 'react';
+import {AbsoluteFill, Sequence, interpolate, useCurrentFrame} from 'remotion';
+
+const panelStyle: React.CSSProperties = {
+ position: 'relative',
+ minWidth: 0,
+ minHeight: 0,
+ border: '2px solid rgba(255, 255, 255, 0.16)',
+ borderRadius: 24,
+ backgroundColor: '#111827',
+ perspective: 900,
+};
+
+const labelStyle: React.CSSProperties = {
+ position: 'absolute',
+ left: 20,
+ top: 16,
+ zIndex: 1,
+ fontFamily: 'Arial, sans-serif',
+ fontSize: 24,
+ fontWeight: 700,
+ color: 'white',
+ pointerEvents: 'none',
+};
+
+const hintStyle: React.CSSProperties = {
+ position: 'absolute',
+ left: 20,
+ bottom: 16,
+ zIndex: 1,
+ fontFamily: 'Arial, sans-serif',
+ fontSize: 16,
+ color: 'rgba(255, 255, 255, 0.68)',
+ pointerEvents: 'none',
+};
+
+const CropContent: React.FC<{
+ readonly color: string;
+ readonly text: string;
+}> = ({color, text}) => {
+ return (
+ <AbsoluteFill
+ style={{
+ alignItems: 'center',
+ justifyContent: 'center',
+ backgroundColor: color,
+ backgroundImage:
+ 'linear-gradient(rgba(255,255,255,0.18) 2px, transparent 2px), linear-gradient(90deg, rgba(255,255,255,0.18) 2px, transparent 2px)',
+ backgroundSize: '48px 48px',
+ color: 'white',
+ fontFamily: 'Arial, sans-serif',
+ fontSize: 44,
+ fontWeight: 800,
+ letterSpacing: 4,
+ }}
+ >
+ {text}
+ </AbsoluteFill>
+ );
+};
+
+export const SequenceCropTest: React.FC = () => {
+ const frame = useCurrentFrame();
+
+ return (
+ <AbsoluteFill
+ style={{
+ backgroundColor: '#070b14',
+ padding: 40,
+ gap: 28,
+ fontFamily: 'Arial, sans-serif',
+ }}
+ >
+ <div style={{height: 76, color: 'white'}}>
+ <div style={{fontSize: 38, fontWeight: 800}}>
+ Sequence crop controls
+ </div>
+ <div style={{fontSize: 18, color: 'rgba(255, 255, 255, 0.62)'}}>
+ Select a named Sequence in the timeline and edit its crop controls.
+ </div>
+ </div>
+ <div
+ style={{
+ flex: 1,
+ display: 'grid',
+ gridTemplateColumns: '1fr 1fr',
+ gridTemplateRows: '1fr 1fr',
+ gap: 28,
+ }}
+ >
+ <div style={panelStyle}>
+ <Sequence
+ name="Static crop β€” edit me"
+ cropLeft={0.15}
+ cropRight={0.08}
+ cropTop={0.12}
+ cropBottom={0.18}
+ >
+ <CropContent color="#2563eb" text="STATIC" />
+ </Sequence>
+ <div style={labelStyle}>Static crop</div>
+ <div style={hintStyle}>All four fields are editable</div>
+ </div>
+
+ <div style={panelStyle}>
+ <Sequence
+ name="Animated crop"
+ cropLeft={interpolate(frame, [0, 60, 119], [0, 0.45, 0], {
+ extrapolateLeft: 'clamp',
+ extrapolateRight: 'clamp',
+ })}
+ cropRight={interpolate(frame, [0, 60, 119], [0, 0.2, 0], {
+ extrapolateLeft: 'clamp',
+ extrapolateRight: 'clamp',
+ })}
+ cropTop={0.08}
+ cropBottom={0.08}
+ >
+ <CropContent color="#7c3aed" text="ANIMATED" />
+ </Sequence>
+ <div style={labelStyle}>Animated crop</div>
+ <div style={hintStyle}>Scrub frames 0–119</div>
+ </div>
+
+ <div
+ style={{
+ ...panelStyle,
+ backgroundImage:
+ 'linear-gradient(90deg, transparent calc(50% - 1px), rgba(255,255,255,0.5) calc(50% - 1px), rgba(255,255,255,0.5) calc(50% + 1px), transparent calc(50% + 1px))',
+ }}
+ >
+ <Sequence
+ name="Overlapping crop β€” midpoint"
+ cropLeft={0.6}
+ cropRight={0.6}
+ >
+ <CropContent color="#dc2626" text="OVERLAP" />
+ </Sequence>
+ <div style={labelStyle}>Overlapping crop</div>
+ <div style={hintStyle}>0.6 + 0.6 collapses at the center line</div>
+ </div>
+
+ <div style={panelStyle}>
+ <Sequence
+ name="Perspective crop β€” inspect outline"
+ cropLeft={0.18}
+ cropRight={0.22}
+ cropTop={0.12}
+ cropBottom={0.16}
+ style={{
+ transform: 'rotateX(-12deg) rotateY(28deg)',
+ transformOrigin: 'center',
+ }}
+ >
+ <CropContent color="#059669" text="3D OUTLINE" />
+ </Sequence>
+ <div style={labelStyle}>Perspective crop</div>
+ <div style={hintStyle}>
+ Select it to inspect the projected outline
+ </div>
+ </div>
+ </div>
+ </AbsoluteFill>
+ );
+};
diff --git a/packages/gif/src/Gif.tsx b/packages/gif/src/Gif.tsx
index c0ad6e357f..8367e579f4 100644
--- a/packages/gif/src/Gif.tsx
+++ b/packages/gif/src/Gif.tsx
@@ -7,6 +7,7 @@ import {
useRemotionEnvironment,
type EffectsProp,
type InteractiveBaseProps,
+ type InteractiveCropProps,
type InteractivePremountProps,
type InteractiveTransformProps,
type SequenceControls,
@@ -19,6 +20,7 @@ import type {RemotionGifProps} from './props';
const {useMemoizedEffectDefinitions, useMemoizedEffects} = Internals;
export type GifProps = InteractiveBaseProps &
+ InteractiveCropProps &
InteractivePremountProps &
InteractiveTransformProps &
RemotionGifProps & {
@@ -45,6 +47,7 @@ export const gifSchema: InteractivitySchema = {
...Internals.transformSchema,
...Interactive.backgroundSchema,
...Interactive.borderSchema,
+ ...Interactive.cropSchema,
} as const satisfies InteractivitySchema;
const GifInner = ({
@@ -66,6 +69,10 @@ const GifInner = ({
styleWhilePremounted,
styleWhilePostmounted,
style,
+ cropLeft,
+ cropRight,
+ cropTop,
+ cropBottom,
controls,
effects = [],
ref,
@@ -94,6 +101,14 @@ const GifInner = ({
styleWhilePostmounted: styleWhilePostmounted ?? null,
hideWhilePremounted: 'display-none',
});
+ const croppedStyle = Internals.useCropStyle({
+ cropLeft,
+ cropRight,
+ cropTop,
+ cropBottom,
+ style: premountingStyle,
+ componentName: '<Gif />',
+ });
const memoizedEffectDefinitions = useMemoizedEffectDefinitions(effects);
const memoizedEffects = useMemoizedEffects({
@@ -115,7 +130,7 @@ const GifInner = ({
id,
delayRenderTimeoutInMilliseconds,
requestInit,
- style: premountingStyle ?? undefined,
+ style: croppedStyle ?? undefined,
effects: memoizedEffects,
};
diff --git a/packages/gif/src/test/Gif.test.tsx b/packages/gif/src/test/Gif.test.tsx
index 786919692a..e7723286e7 100644
--- a/packages/gif/src/test/Gif.test.tsx
+++ b/packages/gif/src/test/Gif.test.tsx
@@ -14,11 +14,15 @@ type RegisteredSequence = {
readonly postmountDisplay: number | null;
};
-test('Gif exposes background and border controls', () => {
+test('Gif exposes background, border, and crop controls', () => {
expect('style.backgroundColor' in gifSchema).toBe(true);
expect('style.borderWidth' in gifSchema).toBe(true);
expect('style.borderStyle' in gifSchema).toBe(true);
expect('style.borderColor' in gifSchema).toBe(true);
+ expect('cropLeft' in gifSchema).toBe(true);
+ expect('cropRight' in gifSchema).toBe(true);
+ expect('cropTop' in gifSchema).toBe(true);
+ expect('cropBottom' in gifSchema).toBe(true);
});
class MockWorker {
@@ -229,6 +233,24 @@ test('<Gif> exposes non-keyframable premounting schema fields', () => {
expect(gifSchema.postmountFor).toMatchObject({keyframable: false});
});
+test('<Gif> applies crop props to its canvas', () => {
+ const {container} = render(
+ <SequenceRegistrationWrapper onRegisterSequence={() => undefined}>
+ <Gif
+ src="test.gif"
+ cropLeft={0.1}
+ cropRight={0.2}
+ cropTop={0.3}
+ cropBottom={0.4}
+ />
+ </SequenceRegistrationWrapper>,
+ );
+
+ expect(container.querySelector('canvas')?.style.clipPath).toBe(
+ 'inset(30% 20% 40% 10%)',
+ );
+});
+
test('<Gif> hides the canvas while premounted and postmounted', () => {
const premounted = render(
<SequenceRegistrationWrapper
diff --git a/packages/media/src/test/border-schema.test.ts b/packages/media/src/test/border-schema.test.ts
index 428bb674a8..b4d23776ff 100644
--- a/packages/media/src/test/border-schema.test.ts
+++ b/packages/media/src/test/border-schema.test.ts
@@ -9,6 +9,23 @@ test('Video exposes background and border controls', () => {
expect('style.borderColor' in videoSchema).toBe(true);
});
+test('Video exposes crop controls', () => {
+ for (const field of [
+ 'cropLeft',
+ 'cropRight',
+ 'cropTop',
+ 'cropBottom',
+ ] as const) {
+ expect(videoSchema[field]).toMatchObject({
+ type: 'number',
+ default: 0,
+ min: 0,
+ max: 1,
+ keyframable: true,
+ });
+ }
+});
+
test('Audio does not expose visual background or border controls', () => {
expect('style.backgroundColor' in audioSchema).toBe(false);
expect('style.borderWidth' in audioSchema).toBe(false);
diff --git a/packages/media/src/test/video-crop.test.tsx b/packages/media/src/test/video-crop.test.tsx
new file mode 100644
index 0000000000..0ff2aca527
--- /dev/null
+++ b/packages/media/src/test/video-crop.test.tsx
@@ -0,0 +1,64 @@
+import {Player} from '@remotion/player';
+import React from 'react';
+import {createRoot} from 'react-dom/client';
+import {expect, test} from 'vitest';
+import {Video} from '../video/video';
+
+const waitFor = async (predicate: () => boolean) => {
+ const started = Date.now();
+ while (Date.now() - started < 10000) {
+ if (predicate()) {
+ return;
+ }
+
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ }
+
+ throw new Error('Timed out waiting for condition');
+};
+
+test('applies crop props to the Video canvas', async () => {
+ const container = document.createElement('div');
+ document.body.appendChild(container);
+
+ const Composition: React.FC = () => {
+ return (
+ <Video
+ cropBottom={0.4}
+ cropLeft={0.1}
+ cropRight={0.2}
+ cropTop={0.3}
+ data-testid="cropped-video"
+ src="/bigbuckbunny.mp4"
+ />
+ );
+ };
+
+ const root = createRoot(container);
+ root.render(
+ <Player
+ acknowledgeRemotionLicense
+ component={Composition}
+ compositionHeight={720}
+ compositionWidth={1280}
+ durationInFrames={100}
+ fps={30}
+ initiallyMuted
+ inputProps={{}}
+ />,
+ );
+
+ try {
+ await waitFor(
+ () => container.querySelector('[data-testid="cropped-video"]') !== null,
+ );
+ const canvas = container.querySelector(
+ '[data-testid="cropped-video"]',
+ ) as HTMLCanvasElement;
+ expect(canvas).toBeInstanceOf(HTMLCanvasElement);
+ expect(canvas.style.clipPath).toBe('inset(30% 20% 40% 10%)');
+ } finally {
+ root.unmount();
+ container.remove();
+ }
+});
diff --git a/packages/media/src/video/props.ts b/packages/media/src/video/props.ts
index 8e716eda13..8dc800509c 100644
--- a/packages/media/src/video/props.ts
+++ b/packages/media/src/video/props.ts
@@ -3,6 +3,7 @@ import type {
EffectDefinitionAndStack,
EffectsProp,
InteractiveBaseProps,
+ InteractiveCropProps,
InteractivePremountProps,
LogLevel,
LoopVolumeCurveBehavior,
@@ -102,4 +103,5 @@ export type VideoProps = MandatoryVideoProps &
Partial<OptionalVideoProps> &
NativeVideoProps &
InteractiveBaseProps &
+ InteractiveCropProps &
InteractivePremountProps;
diff --git a/packages/media/src/video/video.tsx b/packages/media/src/video/video.tsx
index 5accbe0f8e..07bda80b31 100644
--- a/packages/media/src/video/video.tsx
+++ b/packages/media/src/video/video.tsx
@@ -15,8 +15,12 @@ import type {InnerVideoProps, VideoProps} from './props';
import {VideoForPreview} from './video-for-preview';
import {VideoForRendering} from './video-for-rendering';
-const {validateMediaTrimProps, resolveTrimProps, validateMediaProps} =
- Internals;
+const {
+ validateMediaTrimProps,
+ resolveTrimProps,
+ validateMediaProps,
+ useCropStyle,
+} = Internals;
export const videoSchema: InteractivitySchema = {
src: {
@@ -50,6 +54,7 @@ export const videoSchema: InteractivitySchema = {
...Internals.transformSchema,
...Interactive.backgroundSchema,
...Interactive.borderSchema,
+ ...Interactive.cropSchema,
} as const satisfies InteractivitySchema;
const InnerVideo: React.FC<
@@ -235,6 +240,10 @@ const VideoInner: React.FC<
postmountFor,
styleWhilePremounted,
styleWhilePostmounted,
+ cropLeft,
+ cropRight,
+ cropTop,
+ cropBottom,
...props
}) => {
const fallbackLogLevel = Internals.useLogLevel();
@@ -328,6 +337,14 @@ const VideoInner: React.FC<
styleWhilePostmounted: styleWhilePostmounted ?? null,
hideWhilePremounted: 'display-none',
});
+ const croppedStyle = useCropStyle({
+ cropLeft,
+ cropRight,
+ cropTop,
+ cropBottom,
+ style: premountingStyle,
+ componentName: '<Video />',
+ });
if (sequenceDurationInFrames === 0) {
return null;
@@ -379,7 +396,7 @@ const VideoInner: React.FC<
playbackRate={playbackRate ?? 1}
showInTimeline={showInTimeline ?? true}
src={src}
- style={premountingStyle ?? {}}
+ style={croppedStyle ?? {}}
trimAfter={trimAfter}
trimBefore={trimBefore}
volume={volume ?? 1}
diff --git a/packages/rive/package.json b/packages/rive/package.json
index c0a701055a..ca69e9abd1 100644
--- a/packages/rive/package.json
+++ b/packages/rive/package.json
@@ -12,6 +12,7 @@
"formatting": "oxfmt src --check",
"format": "oxfmt src",
"lint": "eslint src",
+ "test": "bun test src/test",
"make": "tsgo -d && bun --env-file=../.env.bundle bundle.ts"
},
"bugs": {
diff --git a/packages/rive/src/RemotionRiveCanvas.tsx b/packages/rive/src/RemotionRiveCanvas.tsx
index 84e9287165..e23ae89e3d 100644
--- a/packages/rive/src/RemotionRiveCanvas.tsx
+++ b/packages/rive/src/RemotionRiveCanvas.tsx
@@ -18,6 +18,7 @@ import React, {
import type {
EffectsProp,
InteractiveBaseProps,
+ InteractiveCropProps,
SequenceControls,
InteractivitySchema,
} from 'remotion';
@@ -60,7 +61,8 @@ type RemotionRiveCanvasOwnProps = {
};
export type RemotionRiveCanvasProps = RemotionRiveCanvasOwnProps &
- InteractiveBaseProps;
+ InteractiveBaseProps &
+ InteractiveCropProps;
export type RiveCanvasRef = {
getAnimationInstance: () => LinearAnimationInstance | null;
@@ -94,7 +96,7 @@ const riveAlignmentVariants: Record<
'top-right': {},
};
-const riveCanvasSchema = {
+export const riveCanvasSchema: InteractivitySchema = {
...Internals.baseSchema,
fit: {
type: 'enum',
@@ -111,7 +113,8 @@ const riveCanvasSchema = {
...Internals.transformSchema,
...Interactive.backgroundSchema,
...Interactive.borderSchema,
-} as const satisfies InteractivitySchema;
+ ...Interactive.cropSchema,
+};
type RemotionRiveCanvasContentProps = Omit<
RemotionRiveCanvasOwnProps,
@@ -122,6 +125,7 @@ type RemotionRiveCanvasContentProps = Omit<
readonly enableRiveAssetCdn: boolean;
readonly effects: EffectsProp;
readonly controls: SequenceControls | undefined;
+ readonly canvasRef: React.RefObject<HTMLCanvasElement | null>;
};
const RemotionRiveCanvasContentForwardRefFunction: React.ForwardRefRenderFunction<
@@ -141,12 +145,12 @@ const RemotionRiveCanvasContentForwardRefFunction: React.ForwardRefRenderFunctio
style,
effects,
controls,
+ canvasRef,
},
ref,
) => {
const {width, fps, height} = useVideoConfig();
const frame = useCurrentFrame();
- const canvas = useRef<HTMLCanvasElement>(null);
const [riveCanvasInstance, setRiveCanvas] = useState<RiveCanvas | null>(null);
const [err, setError] = useState<Error | null>(null);
const {delayRender, continueRender} = useDelayRender();
@@ -285,7 +289,7 @@ const RemotionRiveCanvasContentForwardRefFunction: React.ForwardRefRenderFunctio
return;
}
- const outputCanvas = canvas.current;
+ const outputCanvas = canvasRef.current;
if (!outputCanvas || !sourceCanvas) {
return;
}
@@ -387,6 +391,7 @@ const RemotionRiveCanvasContentForwardRefFunction: React.ForwardRefRenderFunctio
delayRender,
continueRender,
src,
+ canvasRef,
]);
const canvasStyle: React.CSSProperties = useMemo(
@@ -400,7 +405,7 @@ const RemotionRiveCanvasContentForwardRefFunction: React.ForwardRefRenderFunctio
return (
<canvas
- ref={canvas}
+ ref={canvasRef}
width={width}
height={height}
className={className}
@@ -439,6 +444,10 @@ const RemotionRiveCanvasInnerForwardRefFunction: React.ForwardRefRenderFunction<
freeze,
showInTimeline,
hidden,
+ cropLeft,
+ cropRight,
+ cropTop,
+ cropBottom,
...props
},
ref,
@@ -446,6 +455,15 @@ const RemotionRiveCanvasInnerForwardRefFunction: React.ForwardRefRenderFunction<
props satisfies Record<string, never>;
const memoizedEffectDefinitions = useMemoizedEffectDefinitions(effects);
+ const canvasRef = useRef<HTMLCanvasElement | null>(null);
+ const croppedStyle = Internals.useCropStyle({
+ cropLeft,
+ cropRight,
+ cropTop,
+ cropBottom,
+ style: style ?? null,
+ componentName: '<RemotionRiveCanvas />',
+ });
return (
<Sequence
@@ -464,6 +482,7 @@ const RemotionRiveCanvasInnerForwardRefFunction: React.ForwardRefRenderFunction<
durationInFrames={durationInFrames}
controls={controls}
_remotionInternalEffects={memoizedEffectDefinitions}
+ outlineRef={canvasRef}
// 'stack' is in props
{...props}
>
@@ -478,9 +497,10 @@ const RemotionRiveCanvasInnerForwardRefFunction: React.ForwardRefRenderFunction<
assetLoader={assetLoader}
enableRiveAssetCdn={enableRiveAssetCdn}
className={className}
- style={style}
+ style={croppedStyle ?? undefined}
effects={effects}
controls={controls}
+ canvasRef={canvasRef}
/>
</Sequence>
);
diff --git a/packages/rive/src/test/RemotionRiveCanvas.test.ts b/packages/rive/src/test/RemotionRiveCanvas.test.ts
new file mode 100644
index 0000000000..5b3d693a9a
--- /dev/null
+++ b/packages/rive/src/test/RemotionRiveCanvas.test.ts
@@ -0,0 +1,13 @@
+import {expect, test} from 'bun:test';
+import {riveCanvasSchema} from '../RemotionRiveCanvas.js';
+
+test('<RemotionRiveCanvas> exposes crop controls after border controls', () => {
+ const keys = Object.keys(riveCanvasSchema);
+
+ for (const cropProp of ['cropLeft', 'cropRight', 'cropTop', 'cropBottom']) {
+ expect(cropProp in riveCanvasSchema).toBe(true);
+ expect(keys.indexOf(cropProp)).toBeGreaterThan(
+ keys.indexOf('style.borderColor'),
+ );
+ }
+});
diff --git a/packages/rive/tsconfig.json b/packages/rive/tsconfig.json
index df9fc4d3fd..733cfbfb87 100644
--- a/packages/rive/tsconfig.json
+++ b/packages/rive/tsconfig.json
@@ -7,5 +7,6 @@
"jsx": "react-jsx"
},
"include": ["./src"],
+ "exclude": ["./src/test"],
"references": [{"path": "../core"}]
}
diff --git a/packages/studio-server/src/test/discriminated-union-update.test.ts b/packages/studio-server/src/test/discriminated-union-update.test.ts
index c3019d69fa..e5c188ec8c 100644
--- a/packages/studio-server/src/test/discriminated-union-update.test.ts
+++ b/packages/studio-server/src/test/discriminated-union-update.test.ts
@@ -56,6 +56,10 @@ test('Should expose absolute-fill variant fields when active', () => {
'style.borderWidth',
'style.borderStyle',
'style.borderColor',
+ 'cropLeft',
+ 'cropRight',
+ 'cropTop',
+ 'cropBottom',
]);
});
diff --git a/packages/studio-server/src/test/get-all-schema-keys.test.ts b/packages/studio-server/src/test/get-all-schema-keys.test.ts
index 318ecb83cf..b25619266d 100644
--- a/packages/studio-server/src/test/get-all-schema-keys.test.ts
+++ b/packages/studio-server/src/test/get-all-schema-keys.test.ts
@@ -23,6 +23,10 @@ test('getAllSchemaKeys returns every key across all enum variants', () => {
'style.borderWidth',
'style.borderStyle',
'style.borderColor',
+ 'cropLeft',
+ 'cropRight',
+ 'cropTop',
+ 'cropBottom',
'premountFor',
'postmountFor',
'durationInFrames',
diff --git a/packages/studio-shared/src/schema-field-info.ts b/packages/studio-shared/src/schema-field-info.ts
index a5bcd2a1c6..05560a939e 100644
--- a/packages/studio-shared/src/schema-field-info.ts
+++ b/packages/studio-shared/src/schema-field-info.ts
@@ -47,6 +47,7 @@ export type SchemaFieldGroup =
| 'transforms'
| 'background'
| 'border'
+ | 'crop'
| 'text';
export type SchemaFieldGroupInfo = {
@@ -61,6 +62,7 @@ export const SCHEMA_FIELD_GROUPS = [
{id: 'text', label: 'Text'},
{id: 'background', label: 'Background'},
{id: 'border', label: 'Border'},
+ {id: 'crop', label: 'Crop'},
] as const satisfies readonly SchemaFieldGroupInfo[];
const schemaFieldGroupOrder = SCHEMA_FIELD_GROUPS.reduce(
@@ -79,6 +81,13 @@ const TRANSFORM_FIELD_KEYS = new Set([
'style.opacity',
]);
+const CROP_FIELD_KEYS = new Set([
+ 'cropLeft',
+ 'cropRight',
+ 'cropTop',
+ 'cropBottom',
+]);
+
const BORDER_FIELD_KEYS = new Set([
'style.borderWidth',
'style.borderStyle',
@@ -108,6 +117,10 @@ export const getSchemaFieldGroup = (key: string): SchemaFieldGroup => {
return 'transforms';
}
+ if (CROP_FIELD_KEYS.has(key)) {
+ return 'crop';
+ }
+
if (BORDER_FIELD_KEYS.has(key)) {
return 'border';
}
diff --git a/packages/studio-shared/src/test/schema-field-info.test.ts b/packages/studio-shared/src/test/schema-field-info.test.ts
index 6ba6e7b419..6126d6beb6 100644
--- a/packages/studio-shared/src/test/schema-field-info.test.ts
+++ b/packages/studio-shared/src/test/schema-field-info.test.ts
@@ -8,6 +8,7 @@ import {
SCHEMA_FIELD_ROW_HEIGHT,
getEffectFieldsToShow,
getFieldsToShow,
+ getSchemaFieldGroup,
} from '../schema-field-info';
const effect = {
@@ -199,6 +200,11 @@ test('getFieldsToShow sorts fields by inspector group order', () => {
default: 1,
hiddenFromList: false,
},
+ cropLeft: {
+ type: 'number',
+ default: 0,
+ hiddenFromList: false,
+ },
'style.backgroundColor': {
type: 'color',
default: 'transparent',
@@ -261,6 +267,7 @@ test('getFieldsToShow sorts fields by inspector group order', () => {
'style.borderWidth',
'style.borderStyle',
'style.borderColor',
+ 'cropLeft',
]);
expect(fields?.map((field) => field.group)).toEqual([
'source',
@@ -278,9 +285,16 @@ test('getFieldsToShow sorts fields by inspector group order', () => {
'border',
'border',
'border',
+ 'crop',
]);
});
+test('groups Sequence crop controls into the Crop inspector section', () => {
+ expect(
+ ['cropLeft', 'cropRight', 'cropTop', 'cropBottom'].map(getSchemaFieldGroup),
+ ).toEqual(['crop', 'crop', 'crop', 'crop']);
+});
+
test('getFieldsToShow does not reserve extra height for text content fields', () => {
const fields = getFieldsToShow({
schema: {
diff --git a/packages/studio/src/components/SelectedOutlineOverlay.tsx b/packages/studio/src/components/SelectedOutlineOverlay.tsx
index d1728b2083..80991b8b88 100644
--- a/packages/studio/src/components/SelectedOutlineOverlay.tsx
+++ b/packages/studio/src/components/SelectedOutlineOverlay.tsx
@@ -8,7 +8,12 @@ import React, {
useRef,
useState,
} from 'react';
-import {Internals} from 'remotion';
+import {
+ Internals,
+ type GetDragOverrides,
+ type InteractivitySchema,
+ type TSequence,
+} from 'remotion';
import {NoReactInternals} from 'remotion/no-react';
import {StudioServerConnectionCtx} from '../helpers/client-id';
import {isStudioInteractivityEnabled} from '../helpers/interactivity-enabled';
@@ -107,6 +112,50 @@ export {
getTransformedSvgViewportPoints,
} from './selected-outline-measurement';
export {selectedOutlineDragThresholdPx} from './selected-outline-types';
+
+const cropFieldKeys = {
+ left: 'cropLeft',
+ right: 'cropRight',
+ top: 'cropTop',
+ bottom: 'cropBottom',
+} as const;
+
+const getEffectiveCropValue = ({
+ activeSchema,
+ controls,
+ dragOverrides,
+ fieldKey,
+ frame,
+ propStatuses,
+}: {
+ readonly activeSchema: InteractivitySchema | null;
+ readonly controls: NonNullable<TSequence['controls']> | null;
+ readonly dragOverrides: ReturnType<GetDragOverrides>;
+ readonly fieldKey: string;
+ readonly frame: number;
+ readonly propStatuses: ReturnType<typeof Internals.getPropStatusesCtx>;
+}): number => {
+ const fieldSchema = activeSchema?.[fieldKey];
+ if (fieldSchema?.type !== 'number') {
+ return 0;
+ }
+
+ const propStatus = propStatuses?.[fieldKey];
+ const value =
+ propStatus?.status === 'static' || propStatus?.status === 'keyframed'
+ ? Internals.getEffectiveVisualModeValue({
+ propStatus,
+ dragOverrideValue: dragOverrides[fieldKey],
+ defaultValue: fieldSchema.default,
+ frame,
+ shouldResortToDefaultValueIfUndefined: true,
+ })
+ : (controls?.currentRuntimeValueDotNotation[fieldKey] ??
+ fieldSchema.default);
+
+ return typeof value === 'number' && Number.isFinite(value) ? value : 0;
+};
+
export type {
SelectedOutlineDragState,
SelectedOutlineRotationDragState,
@@ -654,6 +703,40 @@ export const SelectedOutlineOverlay: React.FC<{
frame: sourceFrame,
})
: null;
+ const crop = Internals.resolveSequenceCrop({
+ cropLeft: getEffectiveCropValue({
+ activeSchema,
+ controls,
+ dragOverrides,
+ fieldKey: cropFieldKeys.left,
+ frame: sourceFrame,
+ propStatuses: nodePropStatuses,
+ }),
+ cropRight: getEffectiveCropValue({
+ activeSchema,
+ controls,
+ dragOverrides,
+ fieldKey: cropFieldKeys.right,
+ frame: sourceFrame,
+ propStatuses: nodePropStatuses,
+ }),
+ cropTop: getEffectiveCropValue({
+ activeSchema,
+ controls,
+ dragOverrides,
+ fieldKey: cropFieldKeys.top,
+ frame: sourceFrame,
+ propStatuses: nodePropStatuses,
+ }),
+ cropBottom: getEffectiveCropValue({
+ activeSchema,
+ controls,
+ dragOverrides,
+ fieldKey: cropFieldKeys.bottom,
+ frame: sourceFrame,
+ propStatuses: nodePropStatuses,
+ }),
+ });
const fieldSchema = activeSchema?.[translateFieldKey];
const propStatus = nodePropStatuses?.[translateFieldKey];
const scaleFieldSchema = activeSchema?.[scaleFieldKey];
@@ -733,6 +816,7 @@ export const SelectedOutlineOverlay: React.FC<{
controls?.supportsEffects === true;
return {
key,
+ crop,
containsSelection,
effectDrop: canDropEffect
? {
diff --git a/packages/studio/src/components/selected-outline-measurement.ts b/packages/studio/src/components/selected-outline-measurement.ts
index bd7056533b..298a51bbd2 100644
--- a/packages/studio/src/components/selected-outline-measurement.ts
+++ b/packages/studio/src/components/selected-outline-measurement.ts
@@ -310,6 +310,31 @@ const getElementOutlinePoints = (
return quadToPoints(quad, containerRect);
};
+export const cropOutlinePoints = (
+ points: SelectedOutline['points'],
+ crop: SelectedOutlineTarget['crop'],
+): SelectedOutline['points'] => {
+ if (
+ crop.left === 0 &&
+ crop.right === 0 &&
+ crop.top === 0 &&
+ crop.bottom === 0
+ ) {
+ return points;
+ }
+
+ const {left, top} = crop;
+ const right = 1 - crop.right;
+ const bottom = 1 - crop.bottom;
+
+ return [
+ getUvHandlePosition(points, [left, top]),
+ getUvHandlePosition(points, [right, top]),
+ getUvHandlePosition(points, [right, bottom]),
+ getUvHandlePosition(points, [left, bottom]),
+ ];
+};
+
export const getSelectedSequenceKeys = (
selectedItems: readonly TimelineSelection[],
): Set<string> => {
@@ -528,11 +553,13 @@ export const measureOutlines = (
continue;
}
- const points = getElementOutlinePoints(element, containerRect);
- if (points === null) {
+ const uncroppedPoints = getElementOutlinePoints(element, containerRect);
+ if (uncroppedPoints === null) {
continue;
}
+ const points = cropOutlinePoints(uncroppedPoints, target.crop);
+
outlines.push({
key: target.key,
dimensions:
diff --git a/packages/studio/src/components/selected-outline-types.ts b/packages/studio/src/components/selected-outline-types.ts
index 2f287d686c..68592887b5 100644
--- a/packages/studio/src/components/selected-outline-types.ts
+++ b/packages/studio/src/components/selected-outline-types.ts
@@ -29,6 +29,12 @@ export type SelectedOutlineTarget = {
readonly selected: boolean;
readonly selection: TimelineSelection;
readonly sequence: TSequence;
+ readonly crop: {
+ readonly left: number;
+ readonly right: number;
+ readonly top: number;
+ readonly bottom: number;
+ };
readonly drag: SelectedOutlineDragTarget | null;
readonly scaleDrag: SelectedOutlineScaleDragTarget | null;
readonly rotationDrag: SelectedOutlineRotationDragTarget | null;
diff --git a/packages/studio/src/test/timeline-selection.test.ts b/packages/studio/src/test/timeline-selection.test.ts
index 8a2bfd7ae2..9b3c4a8ae7 100644
--- a/packages/studio/src/test/timeline-selection.test.ts
+++ b/packages/studio/src/test/timeline-selection.test.ts
@@ -12,7 +12,10 @@ import {
import {NoReactInternals} from 'remotion/no-react';
import {getInspectorSelectableItems} from '../components/InspectorSequenceSection';
import type {SelectedOutline} from '../components/selected-outline-geometry';
-import {getSelectedTransformOriginInfo} from '../components/selected-outline-measurement';
+import {
+ cropOutlinePoints,
+ getSelectedTransformOriginInfo,
+} from '../components/selected-outline-measurement';
import type {
SelectedOutlineTarget,
SelectedOutlineTransformOriginDragTarget,
@@ -3551,6 +3554,29 @@ test('UV handles use projective projection for perspective quads', () => {
expect(projectedCenter.y).toBeCloseTo(100 / 3, 5);
});
+test('Sequence crops are projected through perspective transforms', () => {
+ const points = [
+ {x: 0, y: 0},
+ {x: 100, y: 0},
+ {x: 150, y: 100},
+ {x: -50, y: 100},
+ ] as const;
+
+ const cropped = cropOutlinePoints(points, {
+ left: 0.25,
+ right: 0.25,
+ top: 0.25,
+ bottom: 0.25,
+ });
+
+ expect(cropped[0].x).toBeCloseTo(150 / 7, 5);
+ expect(cropped[0].y).toBeCloseTo(100 / 7, 5);
+ expect(cropped[1].x).toBeCloseTo(550 / 7, 5);
+ expect(cropped[1].y).toBeCloseTo(100 / 7, 5);
+ expect(cropped[2]).toEqual({x: 90, y: 60});
+ expect(cropped[3]).toEqual({x: 10, y: 60});
+});
+
test('UV handle pointer position maps back to UV coordinates', () => {
const points = [
{x: 20, y: 10},