🎥 Make videos programmatically with React
`@remotion/web-renderer`: linear-gradient support
Jonny Burger7d76e944abc8
diff --git a/packages/web-renderer/src/drawing/draw-element.ts b/packages/web-renderer/src/drawing/draw-element.tsindex de32e0ff0a..36509f356e 100644--- a/packages/web-renderer/src/drawing/draw-element.ts+++ b/packages/web-renderer/src/drawing/draw-element.ts@@ -6,6 +6,10 @@ import {drawOutline} from './draw-outline';import type {DrawFn} from './drawn-fn';import {setOpacity} from './opacity';import {setOverflowHidden} from './overflow';+import {+ createCanvasGradient,+ parseLinearGradient,+} from './parse-linear-gradient';import {setTransform} from './transform';export const drawElement = async ({@@ -28,6 +32,7 @@ export const drawElement = async ({logLevel: LogLevel;}) => {const background = computedStyle.backgroundColor;+ const {backgroundImage} = computedStyle;const borderRadius = parseBorderRadius({borderRadius: computedStyle.borderRadius,width: rect.width,@@ -60,7 +65,27 @@ export const drawElement = async ({forceClipEvenWhenZero: false,});+ // Try to draw linear gradient first+ let gradientDrawn = false;+ if (backgroundImage && backgroundImage !== 'none') {+ const gradientInfo = parseLinearGradient(backgroundImage);+ if (gradientInfo) {+ const gradient = createCanvasGradient({+ ctx: context,+ rect,+ gradientInfo,+ });+ const originalFillStyle = context.fillStyle;+ context.fillStyle = gradient;+ context.fillRect(rect.left, rect.top, rect.width, rect.height);+ context.fillStyle = originalFillStyle;+ gradientDrawn = true;+ }+ }++ // Fallback to solid background color if no gradient was drawnif (+ !gradientDrawn &&background &&background !== 'transparent' &&!(diff --git a/packages/web-renderer/src/drawing/parse-linear-gradient.ts b/packages/web-renderer/src/drawing/parse-linear-gradient.tsnew file mode 100644index 0000000000..95b8bae4e3--- /dev/null+++ b/packages/web-renderer/src/drawing/parse-linear-gradient.ts@@ -0,0 +1,324 @@+import {NoReactInternals} from 'remotion/no-react';++const isValidColor = (color: string): boolean => {+ try {+ const result = NoReactInternals.processColor(color);+ return result !== null && result !== undefined;+ } catch {+ return false;+ }+};++export interface ColorStop {+ color: string; // Normalized CSS color+ position: number; // 0-1, representing position along gradient+}++export interface LinearGradientInfo {+ angle: number; // Degrees, 0 = to top, 90 = to right, 180 = to bottom, 270 = to left+ colorStops: ColorStop[];+}++const parseDirection = (directionStr: string): number => {+ const trimmed = directionStr.trim().toLowerCase();++ // Handle keywords like "to right", "to bottom", etc.+ if (trimmed.startsWith('to ')) {+ const direction = trimmed.substring(3).trim();+ switch (direction) {+ case 'top':+ return 0;+ case 'right':+ return 90;+ case 'bottom':+ return 180;+ case 'left':+ return 270;+ case 'top right':+ case 'right top':+ return 45;+ case 'bottom right':+ case 'right bottom':+ return 135;+ case 'bottom left':+ case 'left bottom':+ return 225;+ case 'top left':+ case 'left top':+ return 315;+ default:+ return 180; // Default to bottom+ }+ }++ // Handle angle values: deg, rad, grad, turn+ const angleMatch = trimmed.match(/^(-?\d+\.?\d*)(deg|rad|grad|turn)$/);+ if (angleMatch) {+ const value = parseFloat(angleMatch[1]);+ const unit = angleMatch[2];++ switch (unit) {+ case 'deg':+ return value;+ case 'rad':+ return (value * 180) / Math.PI;+ case 'grad':+ return (value * 360) / 400;+ case 'turn':+ return value * 360;+ default:+ return value;+ }+ }++ // Default: to bottom+ return 180;+};++const parseColorStops = (colorStopsStr: string): ColorStop[] | null => {+ // Split by comma, but respect parentheses in rgba(), rgb(), hsl(), hsla()+ const parts = colorStopsStr.split(/,(?![^(]*\))/);++ const stops: ColorStop[] = [];++ for (const part of parts) {+ const trimmed = part.trim();+ if (!trimmed) continue;++ // Extract color: can be rgb(), rgba(), hsl(), hsla(), hex, or named color+ const colorMatch = trimmed.match(+ /(rgba?\([^)]+\)|hsla?\([^)]+\)|#[0-9a-f]{3,8}|[a-z]+)/i,+ );++ if (!colorMatch) {+ continue;+ }++ const colorStr = colorMatch[0];++ // Validate that this is actually a valid CSS color+ if (!isValidColor(colorStr)) {+ continue;+ }++ 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;++ // Parse position if provided+ let position: number | null = null;+ if (remaining) {+ const posMatch = remaining.match(/(-?\d+\.?\d*)(%|px)?/);+ if (posMatch) {+ const value = parseFloat(posMatch[1]);+ const unit = posMatch[2];++ if (unit === '%') {+ position = value / 100;+ } else if (unit === 'px') {+ // px values need element dimensions, which we don't have here+ // We'll handle this as a percentage for now (not fully CSS-compliant but good enough)+ position = null;+ } else {+ position = value / 100; // Assume percentage if no unit+ }+ }+ }++ stops.push({+ color: normalizedColor,+ position: position !== null ? position : -1, // -1 means needs to be calculated+ });+ }++ if (stops.length === 0) {+ return null;+ }++ // Distribute positions evenly for stops that don't have explicit positions+ let lastExplicitIndex = -1;+ let lastExplicitPosition = 0;++ for (let i = 0; i < stops.length; i++) {+ if (stops[i].position !== -1) {+ // Found an explicit position+ if (lastExplicitIndex >= 0) {+ // Interpolate between last explicit and current explicit+ const numImplicit = i - lastExplicitIndex - 1;+ if (numImplicit > 0) {+ const step =+ (stops[i].position - lastExplicitPosition) / (numImplicit + 1);+ for (let j = lastExplicitIndex + 1; j < i; j++) {+ stops[j].position =+ lastExplicitPosition + step * (j - lastExplicitIndex);+ }+ }+ } else {+ // Backfill from start to first explicit+ const numImplicit = i;+ if (numImplicit > 0) {+ const step = stops[i].position / (numImplicit + 1);+ for (let j = 0; j < i; j++) {+ stops[j].position = step * (j + 1);+ }+ }+ }++ lastExplicitIndex = i;+ lastExplicitPosition = stops[i].position;+ }+ }++ // If no explicit positions were provided at all, distribute evenly+ // Check this BEFORE handling trailing stops+ if (stops.every((s) => s.position === -1)) {+ if (stops.length === 1) {+ stops[0].position = 0.5;+ } else {+ for (let i = 0; i < stops.length; i++) {+ 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);+ }+ }+ }++ // Clamp positions to 0-1+ for (const stop of stops) {+ stop.position = Math.max(0, Math.min(1, stop.position));+ }++ return stops;+};++const extractGradientContent = (backgroundImage: string): string | null => {+ const prefix = 'linear-gradient(';+ const startIndex = backgroundImage.toLowerCase().indexOf(prefix);+ if (startIndex === -1) {+ return null;+ }++ // Find matching closing parenthesis, handling nested parens from rgb(), rgba(), etc.+ let depth = 0;+ let contentStart = startIndex + prefix.length;+ for (let i = contentStart; i < backgroundImage.length; i++) {+ const char = backgroundImage[i];+ if (char === '(') {+ depth++;+ } else if (char === ')') {+ if (depth === 0) {+ return backgroundImage.substring(contentStart, i).trim();+ }+ depth--;+ }+ }++ return null;+};++export const parseLinearGradient = (+ backgroundImage: string,+): LinearGradientInfo | null => {+ if (!backgroundImage || backgroundImage === 'none') {+ return null;+ }++ const content = extractGradientContent(backgroundImage);++ if (!content) {+ return null;+ }++ // Try to identify the direction/angle part vs color stops+ // Direction/angle is optional and comes first+ // It can be: "to right", "45deg", etc.++ // Split into parts, respecting parentheses+ const parts = content.split(/,(?![^(]*\))/);++ let angle = 180; // Default: to bottom+ let colorStopsStart = 0;++ // Check if first part is a direction/angle+ if (parts.length > 0) {+ const firstPart = parts[0].trim();+ // Check if it looks like a direction or angle (not a color)+ const isDirection =+ firstPart.startsWith('to ') ||+ /^-?\d+\.?\d*(deg|rad|grad|turn)$/.test(firstPart);++ if (isDirection) {+ angle = parseDirection(firstPart);+ colorStopsStart = 1;+ }+ }++ // Parse color stops+ const colorStopsStr = parts.slice(colorStopsStart).join(',');+ const colorStops = parseColorStops(colorStopsStr);++ if (!colorStops || colorStops.length === 0) {+ return null;+ }++ return {+ angle,+ colorStops,+ };+};++export const createCanvasGradient = ({+ ctx,+ rect,+ gradientInfo,+}: {+ ctx: OffscreenCanvasRenderingContext2D;+ rect: DOMRect;+ gradientInfo: LinearGradientInfo;+}): CanvasGradient => {+ // Convert angle to radians+ // CSS angles: 0deg = to top, 90deg = to right, 180deg = to bottom, 270deg = to left+ // We need to calculate the gradient line that spans the rectangle at the given angle++ const angleRad = ((gradientInfo.angle - 90) * Math.PI) / 180;++ const centerX = rect.left + rect.width / 2;+ const centerY = rect.top + rect.height / 2;++ // Calculate gradient line endpoints+ // The gradient line passes through the center and has the specified angle+ const cos = Math.cos(angleRad);+ const sin = Math.sin(angleRad);++ // Find the intersection of the gradient line with the rectangle edges+ const halfWidth = rect.width / 2;+ const halfHeight = rect.height / 2;++ // Calculate the length from center to edge along the gradient line+ const length =+ Math.abs(cos) * halfWidth + Math.abs(sin) * halfHeight ||+ Math.sqrt(halfWidth ** 2 + halfHeight ** 2);++ const x0 = centerX - cos * length;+ const y0 = centerY - sin * length;+ const x1 = centerX + cos * length;+ const y1 = centerY + sin * length;++ const gradient = ctx.createLinearGradient(x0, y0, x1, y1);++ // Add color stops+ for (const stop of gradientInfo.colorStops) {+ gradient.addColorStop(stop.position, stop.color);+ }++ return gradient;+};diff --git a/packages/web-renderer/src/test/Root.tsx b/packages/web-renderer/src/test/Root.tsxindex 043064a589..442bcaae17 100644--- a/packages/web-renderer/src/test/Root.tsx+++ b/packages/web-renderer/src/test/Root.tsx@@ -23,6 +23,7 @@ import {flexPositionedScaled} from './fixtures/flex-positioned-scaled';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 {multiLevelTransformOrigins} from './fixtures/multi-level-transform-origins';import {nestedTranslateScale} from './fixtures/nested-translate-scale';import {opacityInherited} from './fixtures/opacity-inherited';@@ -88,6 +89,7 @@ export const Root: React.FC = () => {</Folder><Composition {...threeDTransformOpacity} /><Composition {...backgroundColor} />+ <Composition {...linearGradient} /><Composition {...outline} /><Composition {...boxShadow} /><Folder name="border">diff --git a/packages/web-renderer/src/test/__screenshots__/linear-gradient.test.tsx/linear-gradient-chromium-darwin.png b/packages/web-renderer/src/test/__screenshots__/linear-gradient.test.tsx/linear-gradient-chromium-darwin.pngnew file mode 100644index 0000000000..3edddabb9eBinary files /dev/null and b/packages/web-renderer/src/test/__screenshots__/linear-gradient.test.tsx/linear-gradient-chromium-darwin.png differdiff --git a/packages/web-renderer/src/test/__screenshots__/linear-gradient.test.tsx/linear-gradient-firefox-darwin.png b/packages/web-renderer/src/test/__screenshots__/linear-gradient.test.tsx/linear-gradient-firefox-darwin.pngnew file mode 100644index 0000000000..74d1266915Binary files /dev/null and b/packages/web-renderer/src/test/__screenshots__/linear-gradient.test.tsx/linear-gradient-firefox-darwin.png differdiff --git a/packages/web-renderer/src/test/__screenshots__/linear-gradient.test.tsx/linear-gradient-webkit-darwin.png b/packages/web-renderer/src/test/__screenshots__/linear-gradient.test.tsx/linear-gradient-webkit-darwin.pngnew file mode 100644index 0000000000..d99ac6aad6Binary files /dev/null and b/packages/web-renderer/src/test/__screenshots__/linear-gradient.test.tsx/linear-gradient-webkit-darwin.png differdiff --git a/packages/web-renderer/src/test/fixtures/linear-gradient.tsx b/packages/web-renderer/src/test/fixtures/linear-gradient.tsxnew file mode 100644index 0000000000..d583655473--- /dev/null+++ b/packages/web-renderer/src/test/fixtures/linear-gradient.tsx@@ -0,0 +1,118 @@+import {AbsoluteFill} from 'remotion';++const Component: React.FC = () => {+ return (+ <AbsoluteFill+ style={{+ backgroundColor: '#f0f0f0',+ padding: 15,+ display: 'flex',+ flexWrap: 'wrap',+ gap: 20,+ }}+ >+ {/* Simple horizontal gradient */}+ <div+ style={{+ width: 100,+ height: 80,+ backgroundImage: 'linear-gradient(to right, red, blue)',+ }}+ />++ {/* Vertical gradient with named colors */}+ <div+ style={{+ width: 100,+ height: 80,+ backgroundImage: 'linear-gradient(to bottom, yellow, purple)',+ }}+ />++ {/* Angle gradient (45deg) */}+ <div+ style={{+ width: 100,+ height: 80,+ backgroundImage: 'linear-gradient(45deg, green, orange)',+ }}+ />++ {/* Multiple color stops with positions */}+ <div+ style={{+ width: 100,+ height: 80,+ backgroundImage:+ 'linear-gradient(to right, red 0%, yellow 50%, blue 100%)',+ }}+ />++ {/* Gradient with rgba colors */}+ <div+ style={{+ width: 100,+ height: 80,+ backgroundImage:+ 'linear-gradient(135deg, rgba(255,0,0,0.5), rgba(0,0,255,0.8))',+ }}+ />++ {/* Gradient with border radius */}+ <div+ style={{+ width: 100,+ height: 80,+ borderRadius: 20,+ backgroundImage: 'linear-gradient(to bottom right, #ff00ff, #00ffff)',+ }}+ />++ {/* Gradient with hex colors */}+ <div+ style={{+ width: 100,+ height: 80,+ backgroundImage: 'linear-gradient(90deg, #ff0000, #0000ff)',+ }}+ />++ {/* Vertical gradient (to top) */}+ <div+ style={{+ width: 100,+ height: 80,+ backgroundImage: 'linear-gradient(to top, black, white)',+ }}+ />++ {/* Default direction (no direction specified = to bottom) */}+ <div+ style={{+ width: 100,+ height: 80,+ backgroundImage: 'linear-gradient(cyan, magenta)',+ }}+ />++ {/* Multiple stops without explicit positions */}+ <div+ style={{+ width: 100,+ height: 80,+ backgroundImage:+ 'linear-gradient(to right, red, yellow, green, blue)',+ }}+ />+ </AbsoluteFill>+ );+};++export const linearGradient = {+ component: Component,+ id: 'linear-gradient',+ width: 700,+ height: 400,+ fps: 25,+ durationInFrames: 1,+} as const;diff --git a/packages/web-renderer/src/test/linear-gradient.test.tsx b/packages/web-renderer/src/test/linear-gradient.test.tsxnew file mode 100644index 0000000000..cfa45fef0d--- /dev/null+++ b/packages/web-renderer/src/test/linear-gradient.test.tsx@@ -0,0 +1,18 @@+import {test} from 'vitest';+import {page} from 'vitest/browser';+import {renderStillOnWeb} from '../render-still-on-web';+import {linearGradient} from './fixtures/linear-gradient';+import {testImage} from './utils';++test('should render linear-gradient', async () => {+ await page.viewport(700, 400);+ const {blob} = await renderStillOnWeb({+ licenseKey: 'free-license',+ composition: linearGradient,+ frame: 0,+ inputProps: {},+ imageFormat: 'png',+ });++ await testImage({blob, testId: 'linear-gradient', threshold: 0.02});+});diff --git a/packages/web-renderer/src/test/parse-linear-gradient.test.tsx b/packages/web-renderer/src/test/parse-linear-gradient.test.tsxnew file mode 100644index 0000000000..4bb3e7d793--- /dev/null+++ b/packages/web-renderer/src/test/parse-linear-gradient.test.tsx@@ -0,0 +1,119 @@+import {describe, expect, test} from 'vitest';+import {parseLinearGradient} from '../drawing/parse-linear-gradient';++describe('parseLinearGradient', () => {+ test('should parse simple gradient with named colors', () => {+ const result = parseLinearGradient('linear-gradient(to right, red, blue)');+ expect(result).not.toBeNull();+ expect(result!.angle).toBe(90);+ expect(result!.colorStops).toHaveLength(2);+ expect(result!.colorStops[0].color).toBe('red');+ expect(result!.colorStops[0].position).toBe(0);+ expect(result!.colorStops[1].color).toBe('blue');+ expect(result!.colorStops[1].position).toBe(1);+ });++ test('should parse gradient with rgb() colors (browser format)', () => {+ const result = parseLinearGradient(+ 'linear-gradient(to right, rgb(255, 0, 0), rgb(0, 0, 255))',+ );+ expect(result).not.toBeNull();+ expect(result!.angle).toBe(90);+ expect(result!.colorStops).toHaveLength(2);+ expect(result!.colorStops[0].color).toBe('rgb(255, 0, 0)');+ expect(result!.colorStops[1].color).toBe('rgb(0, 0, 255)');+ });++ test('should parse gradient with rgba() colors', () => {+ const result = parseLinearGradient(+ 'linear-gradient(135deg, rgba(255, 0, 0, 0.5), rgba(0, 0, 255, 0.8))',+ );+ expect(result).not.toBeNull();+ expect(result!.angle).toBe(135);+ expect(result!.colorStops).toHaveLength(2);+ expect(result!.colorStops[0].color).toBe('rgba(255, 0, 0, 0.5)');+ expect(result!.colorStops[1].color).toBe('rgba(0, 0, 255, 0.8)');+ });++ test('should parse gradient without direction (defaults to 180deg)', () => {+ const result = parseLinearGradient(+ 'linear-gradient(rgb(255, 255, 0), rgb(128, 0, 128))',+ );+ expect(result).not.toBeNull();+ expect(result!.angle).toBe(180);+ expect(result!.colorStops).toHaveLength(2);+ });++ test('should parse gradient with angle in degrees', () => {+ const result = parseLinearGradient(+ 'linear-gradient(45deg, rgb(0, 128, 0), rgb(255, 165, 0))',+ );+ expect(result).not.toBeNull();+ expect(result!.angle).toBe(45);+ expect(result!.colorStops).toHaveLength(2);+ });++ test('should parse gradient with multiple color stops', () => {+ const result = parseLinearGradient(+ 'linear-gradient(to right, rgb(255, 0, 0), rgb(255, 255, 0), rgb(0, 128, 0), rgb(0, 0, 255))',+ );+ expect(result).not.toBeNull();+ expect(result!.colorStops).toHaveLength(4);+ expect(result!.colorStops[0].position).toBe(0);+ expect(result!.colorStops[1].position).toBeCloseTo(0.333, 2);+ expect(result!.colorStops[2].position).toBeCloseTo(0.667, 2);+ expect(result!.colorStops[3].position).toBe(1);+ });++ test('should parse gradient with explicit positions', () => {+ const result = parseLinearGradient(+ 'linear-gradient(to right, red 0%, yellow 50%, blue 100%)',+ );+ expect(result).not.toBeNull();+ expect(result!.colorStops).toHaveLength(3);+ expect(result!.colorStops[0].position).toBe(0);+ expect(result!.colorStops[1].position).toBe(0.5);+ expect(result!.colorStops[2].position).toBe(1);+ });++ test('should parse "to bottom" direction', () => {+ const result = parseLinearGradient('linear-gradient(to bottom, red, blue)');+ expect(result).not.toBeNull();+ expect(result!.angle).toBe(180);+ });++ test('should parse "to top" direction', () => {+ const result = parseLinearGradient('linear-gradient(to top, red, blue)');+ expect(result).not.toBeNull();+ expect(result!.angle).toBe(0);+ });++ test('should parse "to left" direction', () => {+ const result = parseLinearGradient('linear-gradient(to left, red, blue)');+ expect(result).not.toBeNull();+ expect(result!.angle).toBe(270);+ });++ test('should parse "to bottom right" direction', () => {+ const result = parseLinearGradient(+ 'linear-gradient(to bottom right, red, blue)',+ );+ expect(result).not.toBeNull();+ expect(result!.angle).toBe(135);+ });++ test('should parse hex colors', () => {+ const result = parseLinearGradient(+ 'linear-gradient(90deg, #ff0000, #0000ff)',+ );+ expect(result).not.toBeNull();+ expect(result!.colorStops[0].color).toBe('#ff0000');+ expect(result!.colorStops[1].color).toBe('#0000ff');+ });++ test('should return null for invalid input', () => {+ expect(parseLinearGradient('none')).toBeNull();+ expect(parseLinearGradient('')).toBeNull();+ expect(parseLinearGradient('radial-gradient(red, blue)')).toBeNull();+ });+});