Screen-recording a browser animation gives you dropped frames, a mouse cursor and a different video every time. The better way is to let the page draw one exact frame on request, screenshot it, and feed the screenshots to ffmpeg. The result is deterministic: same code, same frames, every time, even on a slow CPU-only machine.
This is how we render short vertical data videos. Below is a stripped-down version you can copy.
Disclosure: I build data tools for AI agents as Fast Data on Apify. This post needs none of them; both files are in our public data-recipes repo.
The one rule: the page never animates itself
The page exposes window.renderFrame(t) and draws everything from t (seconds). No requestAnimationFrame, no setTimeout, no CSS animations, no Math.random() without a seed. If something moves, it moves because renderFrame was called with a later t.
<canvas id="c" width="1080" height="1920"></canvas>
<script>
const ctx = document.getElementById('c').getContext('2d');
const bars = [["Denmark", 42.0], ["Finland", 37.8], ["Germany", 26.0], ["EU average", 20.0], ["Poland", 8.4]];
const ease = x => 1 - Math.pow(1 - Math.min(Math.max(x, 0), 1), 3); // outCubic
window.DURATION = 4;
window.renderFrame = (t) => {
ctx.fillStyle = '#0b1020'; ctx.fillRect(0, 0, 1080, 1920);
ctx.fillStyle = '#fff'; ctx.font = '800 72px sans-serif';
ctx.fillText('Firms using AI, 2025', 80, 330);
bars.forEach(([name, v], i) => {
const p = ease((t - 0.3 - i * 0.25) / 1.2); // staggered grow-in
const y = 520 + i * 190, w = 680 * (v / 42) * p;
ctx.fillStyle = i === 2 ? '#facc15' : '#3b82f6';
ctx.fillRect(80, y, w, 110);
ctx.fillStyle = '#fff'; ctx.font = '700 46px sans-serif';
ctx.fillText(name, 80, y - 18);
ctx.font = '800 56px sans-serif';
ctx.fillText((v * p).toFixed(1) + ' %', 100 + w, y + 75);
});
};
</script>
(The data is Eurostat's 2025 share of enterprises using AI, the same numbers as in an earlier post.)
The capture script
// node capture.mjs index.html out.mp4 [fps]
import { chromium } from 'playwright';
import { spawn } from 'node:child_process';
import { resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
const [html, out, fpsArg] = process.argv.slice(2);
const fps = Number(fpsArg || 30), W = 1080, H = 1920;
const browser = await chromium.launch();
const page = await browser.newPage({ viewport: { width: W, height: H }, deviceScaleFactor: 1 });
page.on('pageerror', e => console.error('PAGE ERROR:', e.message));
await page.goto(pathToFileURL(resolve(html)).href);
await page.evaluate(() => document.fonts.ready);
const duration = await page.evaluate(() => window.DURATION);
const ff = spawn('ffmpeg', ['-y', '-loglevel', 'error', '-f', 'image2pipe', '-framerate', String(fps),
'-c:v', 'png', '-i', '-', '-c:v', 'libx264', '-crf', '18', '-pix_fmt', 'yuv420p',
'-movflags', '+faststart', out], { stdio: ['pipe', 'inherit', 'inherit'] });
const done = new Promise((ok, fail) => ff.on('close', c => (c === 0 ? ok() : fail(new Error('ffmpeg ' + c)))));
const frames = Math.round(duration * fps);
for (let i = 0; i < frames; i++) {
await page.evaluate(([t, i]) => window.renderFrame(t, i), [i / fps, i]); // draw exactly frame i
const png = await page.screenshot({ type: 'png' });
if (!ff.stdin.write(png)) await new Promise(r => ff.stdin.once('drain', r));
}
ff.stdin.end();
await done;
await browser.close();
npm install playwright && npx playwright install chromium
node capture.mjs index.html demo.mp4 30
On a 4-core cloud container without a GPU this produced 120 frames (4 seconds at 30 fps, 1080x1920) in 12.5 seconds including browser start. Heavier scenes with glow, many particles and a simulation run at about 0.25 seconds per frame, so a 15-second clip at 30 fps takes around two minutes.
Why each line is there
| Line | Without it |
|---|---|
deviceScaleFactor: 1 |
on a HiDPI default you get 2160x3840 screenshots and a squashed or oversized video |
await document.fonts.ready |
the first frames render in a fallback font, then the text jumps |
-f image2pipe -c:v png -i - |
no temporary PNG files on disk; ffmpeg reads the stream directly |
stdin.write + drain
|
memory grows without limit when the browser is faster than the encoder |
-pix_fmt yuv420p |
ffmpeg defaults to 4:4:4 from PNG input, and many players and phones show a black screen |
-movflags +faststart |
the video only starts playing in a browser after the whole file has loaded |
pageerror listener |
an exception in renderFrame silently gives you identical frozen frames |
Things that bite later
-
Stepped simulations work, because frames are requested strictly in order: keep a simulation clock and advance it with a fixed
dtuntil it reachest. Never step by "time since last call". -
Audio is a separate pass. Have
renderFramepush events such as{t: 1.25, type: 'hit'}into an array, read it at the end withpage.evaluate, and synthesise or mix the soundtrack to those exact timestamps. Then mux withffmpeg -i video.mp4 -i audio.wav -c:v copy -c:a aac. - WebGL works but is slow on CPU-only machines (software rendering). Canvas 2D is the fastest and most predictable.
- Frame 0 is your thumbnail. In the demo above every value starts at 0.0 %, which is a boring first frame. In our own analytics, short videos that opened with static or identical elements lost far more viewers in the first second than ones that were already moving.
Try it
Both files: snippets/canvas-to-mp4. For 3D, the same idea works with Blender as a Python module; I wrote that up here.
Question: has anyone made this approach work with a real-time library that insists on driving its own clock (some chart libraries do)? I currently patch their timers; I am curious whether there is a cleaner hook.

Top comments (0)