Skip to content

🎥 Make videos programmatically with React

mask image progress

Jonny Burger11fda94ba06b
diff --git a/packages/web-renderer/src/drawing/handle-mask.ts b/packages/web-renderer/src/drawing/handle-mask.ts
new file mode 100644
index 0000000000..e8c0241832
--- /dev/null
+++ b/packages/web-renderer/src/drawing/handle-mask.ts
@@ -0,0 +1,92 @@
+import type {LogLevel} from 'remotion';
+import {compose} from '../compose';
+import {getBiggestBoundingClientRect} from '../get-biggest-bounding-client-rect';
+import type {InternalState} from '../internal-state';
+import {doRectsIntersect} from './do-rects-intersect';
+import type {LinearGradientInfo} from './parse-linear-gradient';
+import {createCanvasGradient} from './parse-linear-gradient';
+import {roundToExpandRect} from './round-to-expand-rect';
+
+export const handleMask = async ({
+ element,
+ parentRect,
+ context,
+ logLevel,
+ internalState,
+ gradientInfo,
+ rect,
+}: {
+ element: HTMLElement | SVGElement;
+ parentRect: DOMRect;
+ context: OffscreenCanvasRenderingContext2D;
+ logLevel: LogLevel;
+ internalState: InternalState;
+ gradientInfo: LinearGradientInfo;
+ rect: DOMRect;
+}) => {
+ const previousMaskImage = element.style.maskImage;
+ const previousWebkitMaskImage = element.style.webkitMaskImage;
+ element.style.maskImage = 'none';
+ element.style.webkitMaskImage = 'none';
+
+ const reset = () => {
+ element.style.maskImage = previousMaskImage;
+ element.style.webkitMaskImage = previousWebkitMaskImage;
+ };
+
+ const boundingRect = roundToExpandRect(getBiggestBoundingClientRect(element));
+
+ if (boundingRect.width <= 0 || boundingRect.height <= 0) {
+ reset();
+ return;
+ }
+
+ if (!doRectsIntersect(boundingRect, parentRect)) {
+ reset();
+ return;
+ }
+
+ const tempCanvas = new OffscreenCanvas(
+ boundingRect.width,
+ boundingRect.height,
+ );
+
+ await compose({
+ element,
+ context: tempCanvas.getContext('2d')!,
+ logLevel,
+ parentRect: boundingRect,
+ internalState,
+ });
+
+ const previousTransform = context.getTransform();
+ const previousCompositeOperation = context.globalCompositeOperation;
+ context.setTransform(1, 0, 0, 1, 0, 0);
+
+ // Apply the mask using destination-in
+ // This keeps only the parts of the fill where the mask has alpha > 0
+ context.globalCompositeOperation = 'destination-in';
+
+ console.log(boundingRect);
+ context.drawImage(
+ tempCanvas,
+ boundingRect.left,
+ boundingRect.top,
+ boundingRect.width,
+ boundingRect.height,
+ );
+
+ const gradient = createCanvasGradient({
+ ctx: context,
+ rect,
+ gradientInfo,
+ });
+
+ context.fillStyle = gradient;
+ context.fillRect(rect.left, rect.top, rect.width, rect.height);
+
+ context.setTransform(previousTransform);
+ context.globalCompositeOperation = previousCompositeOperation;
+
+ reset();
+};
diff --git a/packages/web-renderer/src/drawing/mask-image.ts b/packages/web-renderer/src/drawing/mask-image.ts
new file mode 100644
index 0000000000..c3c0cd6742
--- /dev/null
+++ b/packages/web-renderer/src/drawing/mask-image.ts
@@ -0,0 +1,24 @@
+import type {LinearGradientInfo} from './parse-linear-gradient';
+import {parseLinearGradient} from './parse-linear-gradient';
+
+export const getMaskImageValue = (
+ computedStyle: CSSStyleDeclaration,
+): string | null => {
+ // Check both standard and webkit-prefixed properties
+ const {maskImage, webkitMaskImage} = computedStyle;
+
+ const value = maskImage || webkitMaskImage;
+
+ if (!value || value === 'none') {
+ return null;
+ }
+
+ return value;
+};
+
+export const parseMaskImage = (
+ maskImageValue: string,
+): LinearGradientInfo | null => {
+ // Only linear gradients are supported for now
+ return parseLinearGradient(maskImageValue);
+};
diff --git a/packages/web-renderer/src/drawing/parse-linear-gradient.ts b/packages/web-renderer/src/drawing/parse-linear-gradient.ts
index 95b8bae4e3..3a2b8f4538 100644
--- a/packages/web-renderer/src/drawing/parse-linear-gradient.ts
+++ b/packages/web-renderer/src/drawing/parse-linear-gradient.ts
@@ -101,7 +101,9 @@ const parseColorStops = (colorStopsStr: string): ColorStop[] | null => {
continue;
}
- const remaining = trimmed.substring(colorMatch.index! + colorStr.length).trim();
+ const remaining = trimmed
+ .substring(colorMatch.index! + colorStr.length)
+ .trim();
// Canvas API supports CSS colors directly, so we can use the color string as-is
const normalizedColor = colorStr;
@@ -180,15 +182,11 @@ const parseColorStops = (colorStopsStr: string): ColorStop[] | null => {
stops[i].position = i / (stops.length - 1);
}
}
- } else {
- // Handle trailing stops without explicit positions
- if (lastExplicitIndex < stops.length - 1) {
- const numImplicit = stops.length - 1 - lastExplicitIndex;
- const step = (1 - lastExplicitPosition) / (numImplicit + 1);
- for (let i = lastExplicitIndex + 1; i < stops.length; i++) {
- stops[i].position =
- lastExplicitPosition + step * (i - lastExplicitIndex);
- }
+ } else if (lastExplicitIndex < stops.length - 1) {
+ const numImplicit = stops.length - 1 - lastExplicitIndex;
+ const step = (1 - lastExplicitPosition) / (numImplicit + 1);
+ for (let i = lastExplicitIndex + 1; i < stops.length; i++) {
+ stops[i].position = lastExplicitPosition + step * (i - lastExplicitIndex);
}
}
@@ -209,7 +207,7 @@ const extractGradientContent = (backgroundImage: string): string | null => {
// Find matching closing parenthesis, handling nested parens from rgb(), rgba(), etc.
let depth = 0;
- let contentStart = startIndex + prefix.length;
+ const contentStart = startIndex + prefix.length;
for (let i = contentStart; i < backgroundImage.length; i++) {
const char = backgroundImage[i];
if (char === '(') {
@@ -218,6 +216,7 @@ const extractGradientContent = (backgroundImage: string): string | null => {
if (depth === 0) {
return backgroundImage.substring(contentStart, i).trim();
}
+
depth--;
}
}
diff --git a/packages/web-renderer/src/drawing/process-node.ts b/packages/web-renderer/src/drawing/process-node.ts
index 3773c74bdb..4e97fa33b1 100644
--- a/packages/web-renderer/src/drawing/process-node.ts
+++ b/packages/web-renderer/src/drawing/process-node.ts
@@ -4,6 +4,8 @@ import {calculateTransforms} from './calculate-transforms';
import {drawElement} from './draw-element';
import type {DrawFn} from './drawn-fn';
import {handle3dTransform} from './handle-3d-transform';
+import {handleMask} from './handle-mask';
+import {getMaskImageValue, parseMaskImage} from './mask-image';
export type ProcessNodeReturnValue =
| {type: 'continue'; cleanupAfterChildren: null | (() => void)}
@@ -43,6 +45,33 @@ export const processNode = async ({
return {type: 'continue', cleanupAfterChildren: null};
}
+ const rect = new DOMRect(
+ dimensions.left - parentRect.x,
+ dimensions.top - parentRect.y,
+ dimensions.width,
+ dimensions.height,
+ );
+
+ // Check for mask-image
+ const maskImageValue = getMaskImageValue(computedStyle);
+ const maskGradientInfo = maskImageValue
+ ? parseMaskImage(maskImageValue)
+ : null;
+
+ if (maskGradientInfo) {
+ await handleMask({
+ element,
+ parentRect,
+ context,
+ logLevel,
+ internalState,
+ gradientInfo: maskGradientInfo,
+ rect,
+ });
+ reset();
+ return {type: 'skip-children'};
+ }
+
if (!totalMatrix.is2D) {
await handle3dTransform({
element,
@@ -57,12 +86,7 @@ export const processNode = async ({
}
const {cleanupAfterChildren} = await drawElement({
- rect: new DOMRect(
- dimensions.left - parentRect.x,
- dimensions.top - parentRect.y,
- dimensions.width,
- dimensions.height,
- ),
+ rect,
computedStyle,
context,
draw,
diff --git a/packages/web-renderer/src/test/Root.tsx b/packages/web-renderer/src/test/Root.tsx
index 442bcaae17..5383965f1b 100644
--- a/packages/web-renderer/src/test/Root.tsx
+++ b/packages/web-renderer/src/test/Root.tsx
@@ -24,6 +24,7 @@ import {hugeImageTransform} from './fixtures/huge-image-transform';
import {inside3dTransform} from './fixtures/inside-3d-transform';
import {lineHeight} from './fixtures/line-height';
import {linearGradient} from './fixtures/linear-gradient';
+import {maskImage} from './fixtures/mask-image';
import {multiLevelTransformOrigins} from './fixtures/multi-level-transform-origins';
import {nestedTranslateScale} from './fixtures/nested-translate-scale';
import {opacityInherited} from './fixtures/opacity-inherited';
@@ -89,7 +90,10 @@ export const Root: React.FC = () => {
</Folder>
<Composition {...threeDTransformOpacity} />
<Composition {...backgroundColor} />
- <Composition {...linearGradient} />
+ <Folder name="linear-gradient">
+ <Composition {...maskImage} />
+ <Composition {...linearGradient} />
+ </Folder>
<Composition {...outline} />
<Composition {...boxShadow} />
<Folder name="border">
diff --git a/packages/web-renderer/src/test/fixtures/mask-image.tsx b/packages/web-renderer/src/test/fixtures/mask-image.tsx
new file mode 100644
index 0000000000..cc5ee83d10
--- /dev/null
+++ b/packages/web-renderer/src/test/fixtures/mask-image.tsx
@@ -0,0 +1,110 @@
+import {AbsoluteFill} from 'remotion';
+
+const Component: React.FC = () => {
+ return (
+ <AbsoluteFill
+ style={{
+ backgroundColor: '#f0f0f0',
+ padding: 15,
+ display: 'flex',
+ flexWrap: 'wrap',
+ gap: 20,
+ }}
+ >
+ {/* Horizontal fade from transparent to visible */}
+ <div
+ style={{
+ width: 100,
+ height: 80,
+ backgroundColor: 'red',
+ maskImage: 'linear-gradient(to right, transparent, black)',
+ }}
+ />
+ {/* Vertical fade from visible to transparent */}
+ <div
+ style={{
+ width: 100,
+ height: 80,
+ backgroundColor: 'blue',
+ maskImage: 'linear-gradient(to bottom, black, transparent)',
+ }}
+ />
+ {/* Diagonal fade */}
+ <div
+ style={{
+ width: 100,
+ height: 80,
+ backgroundColor: 'green',
+ maskImage: 'linear-gradient(45deg, transparent, black)',
+ }}
+ />
+ {/* Center fade (visible in middle) */}
+ <div
+ style={{
+ width: 100,
+ height: 80,
+ backgroundColor: 'purple',
+ maskImage:
+ 'linear-gradient(to right, transparent 0%, black 30%, black 70%, transparent 100%)',
+ }}
+ />
+ {/* Mask with gradient background */}
+ <div
+ style={{
+ width: 100,
+ height: 80,
+ backgroundImage: 'linear-gradient(to right, red, blue)',
+ maskImage: 'linear-gradient(to bottom, black, transparent)',
+ }}
+ />
+ {/* Mask with border-radius */}
+ <div
+ style={{
+ width: 100,
+ height: 80,
+ borderRadius: 20,
+ backgroundColor: 'orange',
+ maskImage: 'linear-gradient(to right, transparent, black)',
+ }}
+ />
+ {/* Webkit prefix version */}
+ <div
+ style={{
+ width: 100,
+ height: 80,
+ backgroundColor: 'cyan',
+ WebkitMaskImage: 'linear-gradient(to left, transparent, black)',
+ }}
+ />
+ {/* Using rgba in mask */}
+ <div
+ style={{
+ width: 100,
+ height: 80,
+ backgroundColor: 'magenta',
+ maskImage: 'linear-gradient(to right, rgba(0,0,0,0), rgba(0,0,0,1))',
+ }}
+ />
+ {/* Using rgba in mask */}
+ <div
+ style={{
+ width: 100,
+ height: 80,
+ backgroundColor: 'magenta',
+ maskImage: 'linear-gradient(to right, rgba(0,0,0,0), rgba(0,0,0,1))',
+ }}
+ >
+ <AbsoluteFill style={{backgroundColor: 'blue'}} />
+ </div>
+ </AbsoluteFill>
+ );
+};
+
+export const maskImage = {
+ component: Component,
+ id: 'mask-image',
+ width: 700,
+ height: 300,
+ fps: 25,
+ durationInFrames: 1,
+} as const;
diff --git a/packages/web-renderer/src/test/mask-image.test.tsx b/packages/web-renderer/src/test/mask-image.test.tsx
new file mode 100644
index 0000000000..0642eda013
--- /dev/null
+++ b/packages/web-renderer/src/test/mask-image.test.tsx
@@ -0,0 +1,18 @@
+import {test} from 'vitest';
+import {page} from 'vitest/browser';
+import {renderStillOnWeb} from '../render-still-on-web';
+import {maskImage} from './fixtures/mask-image';
+import {testImage} from './utils';
+
+test('should render mask-image', async () => {
+ await page.viewport(700, 300);
+ const {blob} = await renderStillOnWeb({
+ licenseKey: 'free-license',
+ composition: maskImage,
+ frame: 0,
+ inputProps: {},
+ imageFormat: 'png',
+ });
+
+ await testImage({blob, testId: 'mask-image', threshold: 0.02});
+});