🎥 Make videos programmatically with React
webgl canvas workaround
Jonny Burgerce306f611375
diff --git a/packages/web-renderer/src/drawing/draw-element-to-canvas.ts b/packages/web-renderer/src/drawing/draw-element-to-canvas.tsindex 402a18414c..05e408b2c6 100644--- a/packages/web-renderer/src/drawing/draw-element-to-canvas.ts+++ b/packages/web-renderer/src/drawing/draw-element-to-canvas.ts@@ -1,8 +1,6 @@-import {parseBorderRadius, setBorderRadius} from './border-radius';import {calculateTransforms} from './calculate-transforms';-import {drawBorder} from './draw-border';-import {setOpacity} from './opacity';-import {setTransform} from './transform';+import {drawElement} from './draw-element';+import {transformIn3d} from './transform-in-3d';export const drawElementToCanvas = async ({element,@@ -29,64 +27,39 @@ export const drawElementToCanvas = async ({return;}- const background = computedStyle.backgroundColor;- const borderRadius = parseBorderRadius({- borderRadius: computedStyle.borderRadius,- width: dimensions.width,- height: dimensions.height,- });+ if (!totalMatrix.is2D) {+ const tempCanvas = new OffscreenCanvas(dimensions.width, dimensions.height);+ const context2 = tempCanvas.getContext('2d');+ if (!context2) {+ throw new Error('Could not get context');+ }- const finishTransform = setTransform({- ctx: context,- transform: totalMatrix,- });- const finishBorderRadius = setBorderRadius({- ctx: context,- x: dimensions.left,- y: dimensions.top,- width: dimensions.width,- height: dimensions.height,- borderRadius,- });- const finishOpacity = setOpacity({- ctx: context,- opacity,- });+ await drawElement({+ dimensions,+ computedStyle,+ context: context2,+ draw,+ opacity,+ totalMatrix: new DOMMatrix(),+ });- if (- background &&- background !== 'transparent' &&- !(- background.startsWith('rgba') &&- (background.endsWith(', 0)') || background.endsWith(',0'))- )- ) {- const originalFillStyle = context.fillStyle;- context.fillStyle = background;- context.fillRect(- dimensions.left,- dimensions.top,+ const transformed = transformIn3d(dimensions.width,dimensions.height,+ totalMatrix,+ tempCanvas,);- context.fillStyle = originalFillStyle;+ context.drawImage(transformed, 0, 0);+ } else {+ await drawElement({+ dimensions,+ computedStyle,+ context,+ draw,+ opacity,+ totalMatrix,+ });}- await draw(dimensions, computedStyle);-- drawBorder({- ctx: context,- x: dimensions.left,- y: dimensions.top,- width: dimensions.width,- height: dimensions.height,- borderRadius,- computedStyle,- });-- finishOpacity();- finishBorderRadius();- finishTransform();-reset();};diff --git a/packages/web-renderer/src/drawing/draw-element.ts b/packages/web-renderer/src/drawing/draw-element.tsnew file mode 100644index 0000000000..6fe6873aeb--- /dev/null+++ b/packages/web-renderer/src/drawing/draw-element.ts@@ -0,0 +1,82 @@+import {parseBorderRadius, setBorderRadius} from './border-radius';+import {drawBorder} from './draw-border';+import {setOpacity} from './opacity';+import {setTransform} from './transform';++export const drawElement = async ({+ dimensions,+ computedStyle,+ context,+ draw,+ opacity,+ totalMatrix,+}: {+ dimensions: DOMRect;+ computedStyle: CSSStyleDeclaration;+ context: OffscreenCanvasRenderingContext2D;+ opacity: number;+ totalMatrix: DOMMatrix;+ draw: (+ dimensions: DOMRect,+ computedStyle: CSSStyleDeclaration,+ ) => Promise<void> | void;+}) => {+ const background = computedStyle.backgroundColor;+ const borderRadius = parseBorderRadius({+ borderRadius: computedStyle.borderRadius,+ width: dimensions.width,+ height: dimensions.height,+ });++ const finishTransform = setTransform({+ ctx: context,+ transform: totalMatrix,+ });+ const finishBorderRadius = setBorderRadius({+ ctx: context,+ x: dimensions.left,+ y: dimensions.top,+ width: dimensions.width,+ height: dimensions.height,+ borderRadius,+ });+ const finishOpacity = setOpacity({+ ctx: context,+ opacity,+ });++ if (+ background &&+ background !== 'transparent' &&+ !(+ background.startsWith('rgba') &&+ (background.endsWith(', 0)') || background.endsWith(',0'))+ )+ ) {+ const originalFillStyle = context.fillStyle;+ context.fillStyle = background;+ context.fillRect(+ dimensions.left,+ dimensions.top,+ dimensions.width,+ dimensions.height,+ );+ context.fillStyle = originalFillStyle;+ }++ await draw(dimensions, computedStyle);++ drawBorder({+ ctx: context,+ x: dimensions.left,+ y: dimensions.top,+ width: dimensions.width,+ height: dimensions.height,+ borderRadius,+ computedStyle,+ });++ finishOpacity();+ finishBorderRadius();+ finishTransform();+};diff --git a/packages/web-renderer/src/drawing/transform-in-3d.ts b/packages/web-renderer/src/drawing/transform-in-3d.tsnew file mode 100644index 0000000000..8e98c249b5--- /dev/null+++ b/packages/web-renderer/src/drawing/transform-in-3d.ts@@ -0,0 +1,199 @@+function compileShader(+ shaderGl: WebGLRenderingContext,+ source: string,+ type: number,+) {+ const shader = shaderGl.createShader(type);+ if (!shader) {+ throw new Error('Could not create shader');+ }++ shaderGl.shaderSource(shader, source);+ shaderGl.compileShader(shader);++ if (!shaderGl.getShaderParameter(shader, shaderGl.COMPILE_STATUS)) {+ const log = shaderGl.getShaderInfoLog(shader);+ shaderGl.deleteShader(shader);+ throw new Error('Shader compile error:' + log);+ }++ return shader;+}++export const transformIn3d = (+ canvasWidth: number,+ canvasHeight: number,+ matrix: DOMMatrix,+ sourceCanvas: HTMLCanvasElement | OffscreenCanvas, // Add source canvas parameter+) => {+ const canvas = new OffscreenCanvas(canvasWidth, canvasHeight);+ const gl = canvas.getContext('webgl');++ if (!gl) {+ throw new Error('WebGL not supported');+ }++ // Vertex shader - now includes texture coordinates+ const vsSource = `+ attribute vec2 aPosition;+ attribute vec2 aTexCoord;+ uniform mat4 uTransform;+ uniform mat4 uProjection;+ varying vec2 vTexCoord;++ void main() {+ gl_Position = uProjection * uTransform * vec4(aPosition, 0.0, 1.0);+ vTexCoord = aTexCoord;+ }+ `;++ // Fragment shader - now samples from texture+ const fsSource = `+ precision mediump float;+ uniform sampler2D uTexture;+ varying vec2 vTexCoord;++ void main() {+ gl_FragColor = texture2D(uTexture, vTexCoord);+ }+ `;++ // Create program+ const vertexShader = compileShader(gl, vsSource, gl.VERTEX_SHADER);+ const fragmentShader = compileShader(gl, fsSource, gl.FRAGMENT_SHADER);++ const program = gl.createProgram();+ gl.attachShader(program, vertexShader);+ gl.attachShader(program, fragmentShader);+ gl.linkProgram(program);++ if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {+ throw new Error('Program link error:' + gl.getProgramInfoLog(program));+ }++ gl.useProgram(program);++ // Create a quad (two triangles) with texture coordinates+ const vertices = new Float32Array([+ // Position (x, y) + TexCoord (u, v)+ 0,+ 0,+ 0,+ 0, // bottom-left+ canvasWidth,+ 0,+ 1,+ 0, // bottom-right+ 0,+ canvasHeight,+ 0,+ 1, // top-left+ 0,+ canvasHeight,+ 0,+ 1, // top-left+ canvasWidth,+ 0,+ 1,+ 0, // bottom-right+ canvasWidth,+ canvasHeight,+ 1,+ 1, // top-right+ ]);++ const vertexBuffer = gl.createBuffer();+ gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);+ gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);++ const aPosition = gl.getAttribLocation(program, 'aPosition');+ const aTexCoord = gl.getAttribLocation(program, 'aTexCoord');++ // Position attribute (2 floats, stride 4 floats, offset 0)+ gl.enableVertexAttribArray(aPosition);+ gl.vertexAttribPointer(aPosition, 2, gl.FLOAT, false, 4 * 4, 0);++ // Texture coordinate attribute (2 floats, stride 4 floats, offset 2)+ gl.enableVertexAttribArray(aTexCoord);+ gl.vertexAttribPointer(aTexCoord, 2, gl.FLOAT, false, 4 * 4, 2 * 4);++ // Create and configure texture+ const texture = gl.createTexture();+ gl.bindTexture(gl.TEXTURE_2D, texture);++ // Set texture parameters+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);++ // Upload the source canvas as a texture+ gl.texImage2D(+ gl.TEXTURE_2D,+ 0,+ gl.RGBA,+ gl.RGBA,+ gl.UNSIGNED_BYTE,+ sourceCanvas,+ );++ // The transform matrix+ const transformMatrix = new Float32Array([+ matrix.m11,+ matrix.m12,+ matrix.m13,+ matrix.m14,+ matrix.m21,+ matrix.m22,+ matrix.m23,+ matrix.m24,+ matrix.m31,+ matrix.m32,+ matrix.m33,+ matrix.m34,+ matrix.m41,+ matrix.m42,+ matrix.m43,+ matrix.m44,+ ]);++ // Create orthographic projection matrix for pixel coordinates+ const projectionMatrix = new Float32Array([+ 2 / canvasWidth,+ 0,+ 0,+ 0,+ 0,+ -2 / canvasHeight,+ 0,+ 0,+ 0,+ 0,+ 1,+ 0,+ -1,+ 1,+ 0,+ 1,+ ]);++ const uTransform = gl.getUniformLocation(program, 'uTransform');+ const uProjection = gl.getUniformLocation(program, 'uProjection');+ const uTexture = gl.getUniformLocation(program, 'uTexture');++ gl.uniformMatrix4fv(uTransform, false, transformMatrix);+ gl.uniformMatrix4fv(uProjection, false, projectionMatrix);+ gl.uniform1i(uTexture, 0); // Use texture unit 0++ // Clear and draw+ gl.clearColor(0, 0, 0, 0); // Transparent background+ gl.clear(gl.COLOR_BUFFER_BIT);++ // Enable blending for transparency+ gl.enable(gl.BLEND);+ gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);++ gl.drawArrays(gl.TRIANGLES, 0, 6);++ return canvas;+};diff --git a/packages/web-renderer/src/test/Root.tsx b/packages/web-renderer/src/test/Root.tsxindex d61c75e99f..f6d6f92b73 100644--- a/packages/web-renderer/src/test/Root.tsx+++ b/packages/web-renderer/src/test/Root.tsx@@ -31,6 +31,7 @@ import {paragraphs} from './fixtures/text/paragraphs';import {textFixture} from './fixtures/text/text';import {textTransform} from './fixtures/text/text-transform';import {threeLevelTransformOrigins} from './fixtures/three-level-transform-origins';+import {unwrapped} from './fixtures/unwrapped';export const Root: React.FC = () => {return (@@ -67,6 +68,9 @@ export const Root: React.FC = () => {<Composition {...letterSpacing} /><Composition {...textTransform} /></Folder>+ <Folder name="Projects">+ <Composition {...unwrapped} />+ </Folder></>);};diff --git a/packages/web-renderer/src/test/__screenshots__/transforms.test.tsx/unwrapped-chromium-darwin.png b/packages/web-renderer/src/test/__screenshots__/transforms.test.tsx/unwrapped-chromium-darwin.pngnew file mode 100644index 0000000000..c89461625dBinary files /dev/null and b/packages/web-renderer/src/test/__screenshots__/transforms.test.tsx/unwrapped-chromium-darwin.png differdiff --git a/packages/web-renderer/src/test/transforms.test.tsx b/packages/web-renderer/src/test/transforms.test.tsxindex f51c20fb49..daaf025f61 100644--- a/packages/web-renderer/src/test/transforms.test.tsx+++ b/packages/web-renderer/src/test/transforms.test.tsx@@ -13,6 +13,7 @@ import {rotatedCanvas} from './fixtures/rotated-canvas';import {selfTransformOrigin} from './fixtures/self-transform-origin';import {simpleRotatedSvg} from './fixtures/simple-rotated-svg';import {threeLevelTransformOrigins} from './fixtures/three-level-transform-origins';+import {unwrapped} from './fixtures/unwrapped';import {testImage} from './utils';test('should be able to deal with a simple transform directly on the element', async () => {@@ -150,3 +151,16 @@ test('flex-positioned scaled elements', async () => {await testImage({blob, testId: 'flex-positioned-scaled'});});++test('Github Unwrapped example', async () => {+ await page.viewport(1080, 1080);++ const blob = await renderStillOnWeb({+ composition: unwrapped,+ frame: 0,+ inputProps: {},+ imageFormat: 'png',+ });++ await testImage({blob, testId: 'unwrapped'});+});