Skip to content

🎥 Make videos programmatically with React

`@remotion/canvas-capture-extension`: Always include page background (#10305)

Jonny Burger04897c2d337c
diff --git a/packages/canvas-capture-extension/README.md b/packages/canvas-capture-extension/README.md
index 463c479a35..9600bbc62a 100644
--- a/packages/canvas-capture-extension/README.md
+++ b/packages/canvas-capture-extension/README.md
@@ -1,6 +1,6 @@
# Remotion Canvas Capture Chrome extension
-Record an element—or a whole webpage—as a high-resolution H.264 MP4 or VP9 WebM using Chromium's experimental HTML-in-canvas implementation.
+Record an area—or a whole webpage—as a high-resolution H.264 MP4 or VP9 WebM using Chromium's experimental HTML-in-canvas implementation.
## Pinned browser setup on macOS
@@ -39,6 +39,6 @@ Do not replace this browser with Chrome Canary or a normal Chrome installation:
3. Select `/Users/jonathanburger/Applications/Remotion Canvas Capture Extension`.
4. Enable `chrome://flags/#canvas-draw-element` and restart Chrome if HTML-in-canvas is not already enabled.
-Click the extension icon on a webpage to open the recorder window. Choose H.264 MP4 or VP9 WebM, set the output scale, select an area (the page is focused while you drag, but the recorder window remains open, and the extension picks the deepest DOM element containing the selection) or choose **Whole page**, then press **Record**. The recorder displays the rounded output dimensions and only enables **Record** after the browser confirms that Mediabunny's exact high-quality, realtime configuration is supported. The selected element is drawn at the display's native pixel density, then the crop is copied into a reusable, correctly sized `OffscreenCanvas`. Enable **Include page background** to render the whole page subtree and crop it to the selected area instead of isolating the selected element. Recording continues if the recorder window closes; click the extension icon to reopen it, then press **Stop and open in Convert** to load the recording in [remotion.dev/convert](https://remotion.dev/convert) without downloading it first, or **Stop and download** to save it directly.
+Click the extension icon on a webpage to open the recorder window. Choose H.264 MP4 or VP9 WebM, set the output scale, select an area (the page is focused while you drag, but the recorder window remains open) or choose **Whole page**, then press **Record**. The recorder displays the rounded output dimensions and only enables **Record** after the browser confirms that Mediabunny's exact high-quality, realtime configuration is supported. The whole page subtree is drawn at the display's native pixel density, then the selected crop is copied into a reusable, correctly sized `OffscreenCanvas`. Recording continues if the recorder window closes; click the extension icon to reopen it, then press **Stop and open in Convert** to load the recording in [remotion.dev/convert](https://remotion.dev/convert) without downloading it first, or **Stop and download** to save it directly.
-The chosen element is temporarily placed inside a `layoutSubtree` canvas while recording and restored afterward. Websites that rely on direct-child CSS selectors may look different during capture. Chrome's own pages and the Chrome Web Store do not allow extension script injection.
+The page contents are temporarily placed inside a `layoutSubtree` canvas while recording and restored afterward. Websites that rely on direct-child CSS selectors may look different during capture. Chrome's own pages and the Chrome Web Store do not allow extension script injection.
diff --git a/packages/canvas-capture-extension/popup.css b/packages/canvas-capture-extension/popup.css
index 6022d18192..b6697acd09 100644
--- a/packages/canvas-capture-extension/popup.css
+++ b/packages/canvas-capture-extension/popup.css
@@ -33,8 +33,7 @@ main {
font-weight: 650;
}
-.setting,
-.checkbox {
+.setting {
display: flex;
align-items: center;
justify-content: space-between;
@@ -56,24 +55,6 @@ main {
width: 126px;
}
-.checkbox {
- justify-content: flex-start;
- color: #ddd;
- cursor: pointer;
-}
-
-.checkbox input {
- width: 16px;
- height: 16px;
- margin: 0;
- accent-color: #db2339;
-}
-
-.checkbox:has(input:disabled) {
- cursor: default;
- opacity: 0.45;
-}
-
.row {
display: flex;
gap: 8px;
diff --git a/packages/canvas-capture-extension/popup.html b/packages/canvas-capture-extension/popup.html
index ee0a4e70ab..2b713b9ac4 100644
--- a/packages/canvas-capture-extension/popup.html
+++ b/packages/canvas-capture-extension/popup.html
@@ -32,10 +32,6 @@
<button id="select-area" type="button" disabled>Select area</button>
<button id="whole-page" type="button" disabled>Whole page</button>
</div>
- <label class="checkbox">
- <input id="include-background" type="checkbox" disabled />
- <span>Include page background</span>
- </label>
<div id="target" class="target">Connecting…</div>
<button id="record" class="record" type="button" disabled>Record</button>
<button id="download" type="button" hidden></button>
diff --git a/packages/canvas-capture-extension/src/capture.ts b/packages/canvas-capture-extension/src/capture.ts
index cb323849c8..fadb2b8822 100644
--- a/packages/canvas-capture-extension/src/capture.ts
+++ b/packages/canvas-capture-extension/src/capture.ts
@@ -22,115 +22,13 @@ export type CapturePreflight = {
readonly outputSize: {readonly width: number; readonly height: number};
};
-type WrappedElement = {
+type WrappedPage = {
readonly canvas: HtmlInCanvasElement;
- readonly content: Element;
+ readonly content: HTMLElement;
readonly getSize: () => {readonly width: number; readonly height: number};
readonly restore: () => void;
};
-const copyOuterLayout = ({
- from,
- to,
- width,
- height,
-}: {
- readonly from: Element;
- readonly to: HTMLCanvasElement;
- readonly width: number;
- readonly height: number;
-}) => {
- const computed = window.getComputedStyle(from);
- const properties = [
- 'top',
- 'right',
- 'bottom',
- 'left',
- 'z-index',
- 'float',
- 'clear',
- 'vertical-align',
- 'align-self',
- 'justify-self',
- 'order',
- 'flex',
- 'grid-area',
- 'margin-top',
- 'margin-right',
- 'margin-bottom',
- 'margin-left',
- ] as const;
-
- to.style.boxSizing = 'border-box';
- to.style.display = computed.display === 'inline' ? 'inline-block' : 'block';
- to.style.position =
- computed.position === 'static' ? 'relative' : computed.position;
- to.style.width = `${width}px`;
- to.style.height = `${height}px`;
- for (const property of properties) {
- to.style.setProperty(property, computed.getPropertyValue(property));
- }
-};
-
-const wrapElement = (element: Element): WrappedElement => {
- const parent = element.parentNode;
- if (!parent) {
- throw new Error('The selected element is no longer attached to the page.');
- }
-
- const rect = element.getBoundingClientRect();
- if (rect.width <= 0 || rect.height <= 0) {
- throw new Error('The selected element has no visible size.');
- }
-
- const marker = document.createComment('remotion-canvas-capture');
- const originalStyle = element.getAttribute('style');
- const canvas = document.createElement('canvas') as HtmlInCanvasElement;
- copyOuterLayout({
- from: element,
- to: canvas,
- width: rect.width,
- height: rect.height,
- });
- canvas.layoutSubtree = true;
- canvas.setAttribute('layoutsubtree', '');
-
- parent.insertBefore(marker, element);
- parent.replaceChild(canvas, element);
- canvas.appendChild(element);
-
- if (element instanceof HTMLElement || element instanceof SVGElement) {
- element.style.position = 'absolute';
- element.style.inset = '0';
- element.style.width = '100%';
- element.style.height = '100%';
- element.style.margin = '0';
- }
-
- return {
- canvas,
- content: element,
- getSize: () => ({width: rect.width, height: rect.height}),
- restore: () => {
- if (element instanceof HTMLElement || element instanceof SVGElement) {
- if (originalStyle === null) {
- element.removeAttribute('style');
- } else {
- element.setAttribute('style', originalStyle);
- }
- }
-
- if (canvas.parentNode) {
- canvas.parentNode.replaceChild(element, canvas);
- } else if (marker.parentNode) {
- marker.parentNode.insertBefore(element, marker.nextSibling);
- }
-
- marker.remove();
- },
- };
-};
-
const getPageSize = (
content: HTMLElement,
minimum: {readonly width: number; readonly height: number},
@@ -217,32 +115,13 @@ const validateCaptureSize = ({
};
export const getCapturePreflight = ({
- element,
- wholePage,
scale,
crop,
}: {
- readonly element: Element | null;
- readonly wholePage: boolean;
readonly scale: number;
readonly crop: CaptureCrop | null;
}): CapturePreflight => {
- const sourceSize = wholePage
- ? getWholePageSize()
- : (() => {
- if (!element?.isConnected) {
- throw new Error(
- 'Select an element again; the previous target was removed.',
- );
- }
-
- const rect = element.getBoundingClientRect();
- if (rect.width <= 0 || rect.height <= 0) {
- throw new Error('The selected element has no visible size.');
- }
-
- return {width: rect.width, height: rect.height};
- })();
+ const sourceSize = getWholePageSize();
return {
sourceSize,
outputSize: validateCaptureSize({
@@ -253,7 +132,7 @@ export const getCapturePreflight = ({
};
};
-const wrapWholePage = (): WrappedElement => {
+const wrapWholePage = (): WrappedPage => {
const {body} = document;
const minimumSize = getWholePageSize();
const canvas = document.createElement('canvas') as HtmlInCanvasElement;
@@ -326,8 +205,8 @@ const getFilename = (format: CaptureFormat) => {
return `remotion-capture-${host}-${timestamp}.${format}`;
};
-export class ElementCapture {
- readonly #wrapped: WrappedElement;
+export class PageCapture {
+ readonly #wrapped: WrappedPage;
readonly #scale: number;
readonly #format: CaptureFormat;
readonly #crop: CaptureCrop | null;
@@ -341,14 +220,10 @@ export class ElementCapture {
#paintError: unknown = null;
constructor({
- element,
- wholePage,
scale,
format,
crop,
}: {
- readonly element: Element | null;
- readonly wholePage: boolean;
readonly scale: number;
readonly format: CaptureFormat;
readonly crop: CaptureCrop | null;
@@ -358,14 +233,10 @@ export class ElementCapture {
this.#crop = crop;
this.#matteColors = [
'#fff',
- ...(wholePage
- ? [
- window.getComputedStyle(document.documentElement).backgroundColor,
- window.getComputedStyle(document.body).backgroundColor,
- ]
- : []),
+ window.getComputedStyle(document.documentElement).backgroundColor,
+ window.getComputedStyle(document.body).backgroundColor,
];
- this.#wrapped = wholePage ? wrapWholePage() : wrapElement(element!);
+ this.#wrapped = wrapWholePage();
const context = this.#wrapped.canvas.getContext(
'2d',
) as HtmlInCanvasRenderingContext2D | null;
diff --git a/packages/canvas-capture-extension/src/content.ts b/packages/canvas-capture-extension/src/content.ts
index cb60bd3101..6f4caad2d0 100644
--- a/packages/canvas-capture-extension/src/content.ts
+++ b/packages/canvas-capture-extension/src/content.ts
@@ -1,4 +1,4 @@
-import {type CaptureCrop, ElementCapture, getCapturePreflight} from './capture';
+import {type CaptureCrop, getCapturePreflight, PageCapture} from './capture';
import {openCaptureInConvert} from './handoff';
import {
isCaptureControllerRequest,
@@ -7,11 +7,7 @@ import {
type CaptureControllerState,
} from './messages';
import {canEncodeCapture, isHtmlInCanvasAvailable} from './recorder';
-import {
- findLowestElementContainingRectangle,
- makeSelectionRectangle,
- type SelectionRectangle,
-} from './selection';
+import {makeSelectionRectangle, type SelectionRectangle} from './selection';
type ExtensionController = {
readonly handleRequest: (
@@ -25,13 +21,7 @@ type ExtensionWindow = Window & {
type SelectedTarget =
| {readonly type: 'whole-page'}
- | {readonly type: 'page-crop'; readonly crop: CaptureCrop}
- | {
- readonly type: 'element-crop';
- readonly element: Element;
- readonly elementCrop: CaptureCrop;
- readonly pageCrop: CaptureCrop;
- };
+ | {readonly type: 'page-crop'; readonly crop: CaptureCrop};
const extensionWindow = window as ExtensionWindow;
@@ -46,15 +36,6 @@ const downloadFile = (file: File) => {
URL.revokeObjectURL(url);
};
-const describeElement = (element: Element) => {
- const id = element.id ? `#${element.id}` : '';
- const className =
- element.classList.length > 0
- ? `.${[...element.classList].slice(0, 2).join('.')}`
- : '';
- return `${element.tagName.toLowerCase()}${id}${className}`;
-};
-
const getContainerLabel = (format: CaptureFormat) =>
format === 'mp4' ? 'MP4' : 'WebM';
@@ -119,12 +100,11 @@ const createController = (): ExtensionController => {
shadow.append(style, highlight, selectionLayer);
let selectedTarget: SelectedTarget | null = null;
- let capture: ElementCapture | null = null;
+ let capture: PageCapture | null = null;
let finalizing = false;
let selecting = false;
let scale = Math.max(1, window.devicePixelRatio);
let format: CaptureFormat = 'mp4';
- let includePageBackground = false;
let encoderSupport: CaptureControllerState['encoderSupport'] = 'unavailable';
let outputSize: CaptureControllerState['outputSize'] = null;
let encoderSupportCheckId = 0;
@@ -150,15 +130,7 @@ const createController = (): ExtensionController => {
return 'Whole page';
}
- if (selectedTarget.type === 'page-crop') {
- return `Page crop (${Math.round(selectedTarget.crop.width)}×${Math.round(selectedTarget.crop.height)})`;
- }
-
- if (includePageBackground) {
- return `Page crop with background (${Math.round(selectedTarget.pageCrop.width)}×${Math.round(selectedTarget.pageCrop.height)})`;
- }
-
- return `${describeElement(selectedTarget.element)} crop (${Math.round(selectedTarget.elementCrop.width)}×${Math.round(selectedTarget.elementCrop.height)})`;
+ return `Page crop (${Math.round(selectedTarget.crop.width)}×${Math.round(selectedTarget.crop.height)})`;
};
const resolveCaptureTarget = () => {
@@ -167,26 +139,10 @@ const createController = (): ExtensionController => {
}
if (selectedTarget.type === 'whole-page') {
- return {element: null, wholePage: true, crop: null};
- }
-
- if (selectedTarget.type === 'page-crop') {
- return {element: null, wholePage: true, crop: selectedTarget.crop};
- }
-
- if (includePageBackground) {
- return {
- element: null,
- wholePage: true,
- crop: selectedTarget.pageCrop,
- };
+ return {crop: null};
}
- return {
- element: selectedTarget.element,
- wholePage: false,
- crop: selectedTarget.elementCrop,
- };
+ return {crop: selectedTarget.crop};
};
const refreshEncoderSupport = async () => {
@@ -211,8 +167,6 @@ const createController = (): ExtensionController => {
try {
const preflight = getCapturePreflight({
- element: target.element,
- wholePage: target.wholePage,
scale,
crop: target.crop,
});
@@ -272,7 +226,7 @@ const createController = (): ExtensionController => {
const target = resolveCaptureTarget();
let rect: Pick<DOMRect, 'left' | 'top' | 'width' | 'height'> | null = null;
- if (target?.wholePage && target.crop) {
+ if (target?.crop) {
const pageRect = document.body.getBoundingClientRect();
rect = {
left: pageRect.left + target.crop.left,
@@ -280,16 +234,6 @@ const createController = (): ExtensionController => {
width: target.crop.width,
height: target.crop.height,
};
- } else if (target?.element?.isConnected) {
- const elementRect = target.element.getBoundingClientRect();
- rect = target.crop
- ? {
- left: elementRect.left + target.crop.left,
- top: elementRect.top + target.crop.top,
- width: target.crop.width,
- height: target.crop.height,
- }
- : elementRect;
}
if (!rect) {
@@ -315,7 +259,6 @@ const createController = (): ExtensionController => {
finalizing,
scale,
format,
- includePageBackground,
status,
error: statusIsError,
});
@@ -355,32 +298,11 @@ const createController = (): ExtensionController => {
selectionLayer.style.display = 'none';
selectionBox.style.display = 'none';
- const target = findLowestElementContainingRectangle({
- selection,
- excludedElement: host,
- });
- if (!target) {
- setStatus('No element encompasses that rectangle.', true);
- return;
- }
-
- const pageCrop = getCropRelativeTo(
+ const crop = getCropRelativeTo(
selection,
document.body.getBoundingClientRect(),
);
- if (target === document.body || target === document.documentElement) {
- selectedTarget = {type: 'page-crop', crop: pageCrop};
- } else {
- selectedTarget = {
- type: 'element-crop',
- element: target,
- elementCrop: getCropRelativeTo(
- selection,
- target.getBoundingClientRect(),
- ),
- pageCrop,
- };
- }
+ selectedTarget = {type: 'page-crop', crop};
encoderSupportKey = null;
refreshEncoderSupport().catch(() => undefined);
@@ -423,11 +345,7 @@ const createController = (): ExtensionController => {
}
});
- const setOptions = (
- nextScale: number,
- nextFormat: CaptureFormat,
- nextIncludePageBackground: boolean,
- ) => {
+ const setOptions = (nextScale: number, nextFormat: CaptureFormat) => {
if (!Number.isFinite(nextScale) || nextScale <= 0) {
encoderSupportCheckId++;
encoderSupport = 'unsupported';
@@ -446,17 +364,12 @@ const createController = (): ExtensionController => {
return false;
}
- if (
- scale !== nextScale ||
- format !== nextFormat ||
- includePageBackground !== nextIncludePageBackground
- ) {
+ if (scale !== nextScale || format !== nextFormat) {
encoderSupportKey = null;
}
scale = nextScale;
format = nextFormat;
- includePageBackground = nextIncludePageBackground;
updateHighlight();
return true;
};
@@ -500,13 +413,7 @@ const createController = (): ExtensionController => {
if (request.command === 'set-options') {
if (!capture && !finalizing) {
- if (
- setOptions(
- request.scale,
- request.format,
- request.includePageBackground,
- )
- ) {
+ if (setOptions(request.scale, request.format)) {
await refreshEncoderSupport();
}
}
@@ -558,13 +465,7 @@ const createController = (): ExtensionController => {
return getState();
}
- if (
- !setOptions(
- request.scale,
- request.format,
- request.includePageBackground,
- )
- ) {
+ if (!setOptions(request.scale, request.format)) {
return getState();
}
@@ -579,23 +480,8 @@ const createController = (): ExtensionController => {
return getState();
}
- if (!target.wholePage && !target.element?.isConnected) {
- selectedTarget = null;
- encoderSupport = 'unavailable';
- encoderSupportKey = null;
- outputSize = null;
- setStatus(
- 'Select an element again; the previous target was removed.',
- true,
- );
- updateHighlight();
- return getState();
- }
-
try {
- capture = new ElementCapture({
- element: target.element,
- wholePage: target.wholePage,
+ capture = new PageCapture({
scale,
format,
crop: target.crop,
diff --git a/packages/canvas-capture-extension/src/messages.ts b/packages/canvas-capture-extension/src/messages.ts
index a86cd91e3b..f380f07f62 100644
--- a/packages/canvas-capture-extension/src/messages.ts
+++ b/packages/canvas-capture-extension/src/messages.ts
@@ -38,7 +38,6 @@ export type CaptureControllerState = {
readonly finalizing: boolean;
readonly scale: number;
readonly format: CaptureFormat;
- readonly includePageBackground: boolean;
readonly status: string;
readonly error: boolean;
};
@@ -53,7 +52,6 @@ export type CaptureControllerRequest =
readonly command: 'set-options';
readonly scale: number;
readonly format: CaptureFormat;
- readonly includePageBackground: boolean;
}
| {
readonly type: typeof captureControllerMessageType;
@@ -72,7 +70,6 @@ export type CaptureControllerRequest =
readonly command: 'start-recording';
readonly scale: number;
readonly format: CaptureFormat;
- readonly includePageBackground: boolean;
}
| {
readonly type: typeof captureControllerMessageType;
diff --git a/packages/canvas-capture-extension/src/popup.ts b/packages/canvas-capture-extension/src/popup.ts
index 4c36f2c2db..91cf595e76 100644
--- a/packages/canvas-capture-extension/src/popup.ts
+++ b/packages/canvas-capture-extension/src/popup.ts
@@ -19,7 +19,6 @@ const scaleInput = getElement<HTMLInputElement>('scale');
const formatInput = getElement<HTMLSelectElement>('format');
const selectAreaButton = getElement<HTMLButtonElement>('select-area');
const wholePageButton = getElement<HTMLButtonElement>('whole-page');
-const backgroundInput = getElement<HTMLInputElement>('include-background');
const recordButton = getElement<HTMLButtonElement>('record');
const downloadButton = getElement<HTMLButtonElement>('download');
const target = getElement<HTMLDivElement>('target');
@@ -39,7 +38,6 @@ const disableControls = () => {
formatInput.disabled = true;
selectAreaButton.disabled = true;
wholePageButton.disabled = true;
- backgroundInput.disabled = true;
recordButton.disabled = true;
downloadButton.hidden = true;
};
@@ -70,10 +68,8 @@ const render = (state: CaptureControllerState) => {
}
formatInput.value = state.format;
- backgroundInput.checked = state.includePageBackground;
scaleInput.disabled = controlsDisabled || state.recording;
formatInput.disabled = controlsDisabled || state.recording;
- backgroundInput.disabled = controlsDisabled || state.recording;
selectAreaButton.disabled = controlsDisabled || state.recording;
selectAreaButton.textContent = state.selecting
? 'Cancel selection'
@@ -150,7 +146,6 @@ const runCommand = async (request: CaptureControllerRequest) => {
const getOptions = () => ({
scale: scaleInput.valueAsNumber,
format: formatInput.value as CaptureFormat,
- includePageBackground: backgroundInput.checked,
});
const focusTargetPage = async () => {
@@ -202,7 +197,6 @@ const updateOptions = () => {
scaleInput.addEventListener('change', updateOptions);
formatInput.addEventListener('change', updateOptions);
-backgroundInput.addEventListener('change', updateOptions);
recordButton.addEventListener('click', () => {
if (currentState?.recording) {
diff --git a/packages/canvas-capture-extension/src/selection.ts b/packages/canvas-capture-extension/src/selection.ts
index 671f2ae56b..a033aa8b19 100644
--- a/packages/canvas-capture-extension/src/selection.ts
+++ b/packages/canvas-capture-extension/src/selection.ts
@@ -7,79 +7,6 @@ export type SelectionRectangle = {
readonly height: number;
};
-const containsRectangle = (element: Element, selection: SelectionRectangle) => {
- const rect = element.getBoundingClientRect();
- const tolerance = 0.5;
- return (
- rect.width > 0 &&
- rect.height > 0 &&
- rect.left <= selection.left + tolerance &&
- rect.top <= selection.top + tolerance &&
- rect.right >= selection.right - tolerance &&
- rect.bottom >= selection.bottom - tolerance
- );
-};
-
-const getDepth = (element: Element) => {
- let depth = 0;
- let current: Element | null = element;
- while (current) {
- depth++;
- current = current.parentElement;
- }
-
- return depth;
-};
-
-export const findLowestElementContainingRectangle = ({
- selection,
- excludedElement,
-}: {
- readonly selection: SelectionRectangle;
- readonly excludedElement: Element;
-}) => {
- const inset = Math.min(1, selection.width / 4, selection.height / 4);
- const points = [
- [selection.left + inset, selection.top + inset],
- [selection.right - inset, selection.top + inset],
- [selection.left + inset, selection.bottom - inset],
- [selection.right - inset, selection.bottom - inset],
- [
- selection.left + selection.width / 2,
- selection.top + selection.height / 2,
- ],
- ] as const;
- const candidates = new Set<Element>();
-
- for (const [x, y] of points) {
- for (const hit of document.elementsFromPoint(x, y)) {
- let current: Element | null = hit;
- while (current) {
- if (current !== excludedElement && !excludedElement.contains(current)) {
- candidates.add(current);
- }
-
- current = current.parentElement;
- }
- }
- }
-
- return (
- [...candidates]
- .filter((element) => containsRectangle(element, selection))
- .sort((a, b) => {
- const depthDifference = getDepth(b) - getDepth(a);
- if (depthDifference !== 0) {
- return depthDifference;
- }
-
- const aRect = a.getBoundingClientRect();
- const bRect = b.getBoundingClientRect();
- return aRect.width * aRect.height - bRect.width * bRect.height;
- })[0] ?? null
- );
-};
-
export const makeSelectionRectangle = (
startX: number,
startY: number,