We needed to turn animated HTML templates (charts that grow, captions that slide in, a progress bar synced to a voice-over) into 1080p MP4 files on a server. The first version opened the page in headless Chrome and recorded the screen. Every output stuttered in a different place, and two renders of the same template were never identical byte for byte, which made our visual regression tests useless.

The root issue is that a browser renders on its own schedule. If the machine is busy for 80 ms, the page simply skips ahead, and a real-time recorder captures whatever happened to be on screen. To get smooth, repeatable video you have to stop the page from following wall-clock time and advance it yourself, one frame at a time.

This guide covers the two capture strategies, how to control time inside the page, how to pipe frames into ffmpeg without writing thousands of PNGs to disk, and the GPU flags that decide whether WebGL content renders at all in a container.

Two ways to get frames out of Chrome

Approach

How it works

Good for

Weak spot

Real-time screencast

Chrome pushes a frame each time it paints (Page.startScreencast in the DevTools Protocol, Playwright recordVideo, Puppeteer page.screencast())

Debug recordings, test failure videos

Frame rate follows the machine, frames are dropped under load, output varies per run

Deterministic frame capture

You freeze time, advance it by exactly 1/fps, take a screenshot, repeat

Product videos, social clips, anything rendered at scale

Slower than real time; you must control every time source the page uses

Screencasts are fine when a human only needs to see roughly what happened. For output that customers watch, we switched to deterministic capture. A 10-second clip at 30 fps is 300 screenshots; on a 4-vCPU container that took about 25 seconds, which was acceptable for a background job.

Controlling time inside the page

A page can observe time through several sources, and every one of them must follow your clock, or parts of the animation will drift:

  • Date.now(), new Date() and performance.now()

  • setTimeout and setInterval

  • requestAnimationFrame callbacks

  • CSS animations and transitions, and the Web Animations API

  • <video> and <audio> playback

Option 1: a fake clock in JavaScript

Playwright ships a clock API that replaces the JavaScript time sources. You install it before navigation, pause it, then move it forward explicitly.

import { chromium } from 'playwright';

const fps = 30;
const browser = await chromium.launch();
const page = await browser.newPage({ viewport: { width: 1920, height: 1080 } });

await page.clock.install({ time: new Date('2026-01-01T00:00:00Z') });
await page.goto('https://render.example.com/templates/launch-video');
await page.clock.pauseAt(new Date('2026-01-01T00:00:00Z'));

for (let i = 0; i < 10 * fps; i++) {
  await page.clock.runFor(1000 / fps);       // fires timers and rAF due in this slice
  const png = await page.screenshot({ type: 'png' });
  // hand png to the encoder (next section)
}

The fake clock covers Date, timers and requestAnimationFrame. It does not drive CSS animations or media elements, because those run inside the rendering engine, not in JavaScript.

Option 2: seek CSS animations explicitly

For CSS and Web Animations, the reliable approach is to pause them all and set currentTime before each capture:

async function seekAnimations(page, ms) {
  await page.evaluate((t) => {
    for (const anim of document.getAnimations()) {
      anim.pause();
      anim.currentTime = t;
    }
  }, ms);
}

document.getAnimations() returns CSS animations, CSS transitions and script-created animations in the document. Animations created later (for example, when a class is added by a timer) appear on later calls, so run this every frame rather than once.

Option 3: video elements

If the template embeds a video, seek it and wait for the seeked event before taking the screenshot. Otherwise you capture whichever frame the decoder had ready.

await page.evaluate(async (t) => {
  const v = document.querySelector('video');
  v.pause();
  v.currentTime = t / 1000;
  await new Promise((r) => v.addEventListener('seeked', r, { once: true }));
}, ms);

Option 4: virtual time and BeginFrame in the DevTools Protocol

The DevTools Protocol has Emulation.setVirtualTimePolicy, which lets Chrome itself run on a virtual clock with a time budget, and HeadlessExperimental.beginFrame, which lets the client trigger each compositor frame and receive a screenshot from it. Both are marked experimental. beginFrame is only available in chrome-headless-shell launched with --enable-begin-frame-control, not in the new headless mode of regular Chrome. We tested it and it produced the most exact frames, but we chose the JavaScript-level approach because it works in both Playwright and Puppeteer and does not depend on an experimental domain that can change between Chrome releases.

Piping frames into ffmpeg

Writing every frame to disk and running ffmpeg afterwards works, but it doubles I/O and needs gigabytes of scratch space for long clips. Instead, start ffmpeg once and stream PNG frames to its standard input with the image2pipe demuxer.

import { spawn } from 'node:child_process';

function startEncoder(outFile, fps) {
  const ff = spawn('ffmpeg', [
    '-y',
    '-f', 'image2pipe',
    '-framerate', String(fps),
    '-i', '-',
    '-c:v', 'libx264',
    '-pix_fmt', 'yuv420p',
    '-preset', 'medium',
    '-crf', '20',
    '-movflags', '+faststart',
    outFile,
  ], { stdio: ['pipe', 'inherit', 'inherit'] });
  return ff;
}

const ff = startEncoder('/tmp/out.mp4', fps);
for (let i = 0; i < totalFrames; i++) {
  await page.clock.runFor(1000 / fps);
  await seekAnimations(page, (i * 1000) / fps);
  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 new Promise((r, j) => ff.on('close', (c) => (c === 0 ? r() : j(new Error(`ffmpeg ${c}`)))));

Details that cost us time:

  • Respect backpressure. Without the drain wait, Node buffers every frame in memory when ffmpeg is slower than Chrome. A 60-second 1080p render grew the worker to several gigabytes before we added it.

  • -pix_fmt yuv420p is needed for playback in QuickTime, Safari and most phones. The PNG input is RGB, and without this flag libx264 picks a 4:4:4 format many players reject.

  • -movflags +faststart moves the index to the front of the file so the video can start playing before it is fully downloaded.

  • Use PNG, not JPEG, for intermediate frames. JPEG frames add a second round of compression artefacts, which are especially visible on text and flat colours.

Viewport, device scale factor and output size

Set the viewport to the exact output size. If you need a sharper result for text-heavy templates, render at deviceScaleFactor: 2 and let ffmpeg downscale with -vf scale=1920:1080:flags=lanczos. This costs four times the pixels per screenshot, so measure before turning it on for everything.

libx264 with yuv420p requires even width and height. A viewport of 1081 pixels fails with an encoder error, so round dimensions to even numbers when templates choose their own size.

GPU flags in containers

Headless Chrome in a container usually has no GPU. Canvas 2D and CSS render fine on the CPU, but WebGL content (maps, 3D charts, shader effects) needs a GL implementation.

  • Without a GPU, Chrome can use SwiftShader, a CPU implementation of the graphics APIs, through ANGLE.

  • Recent Chrome versions no longer fall back to SwiftShader for WebGL automatically. To opt in, launch with --enable-unsafe-swiftshader. Only do this for trusted content: the Chromium team made it opt-in because the software path is a weaker security boundary.

  • If you have a GPU node, check what Chrome actually uses by opening chrome://gpu in the same headless setup and saving it as a PDF or screenshot.

const browser = await chromium.launch({
  args: ['--enable-unsafe-swiftshader'],   // only for our own templates, never user URLs
});

Test WebGL output with the exact flags you run in production; a template can look correct on a laptop GPU and render a blank canvas in the container.

Making renders repeatable

Deterministic time is only one input. These also changed our output between runs:

  • Fonts. Install the exact fonts into the image or load them with @font-face, then wait for document.fonts.ready before the first frame.

  • Network. Preload or bundle assets. A slow image request changes what the first frames show.

  • Randomness. Seed Math.random in the template or replace it with a seeded generator for render mode.

  • Chrome version. Pin the browser build. Skia and font rasterisation changes between major versions produce small pixel differences.

Common mistakes

Mistake

Why it hurts

Do this instead

Recording a screencast for final output

Frame rate follows CPU load, frames drop

Freeze time and capture each frame

Faking Date only

requestAnimationFrame and CSS keep running on real time

Use a full clock plus explicit animation seeking

Ignoring stdin backpressure

Worker memory grows with clip length

Wait for drain

Omitting -pix_fmt yuv420p

Files fail to play on Apple devices

Always set it for H.264 delivery

Enabling SwiftShader for any URL

Software GL is a weaker security boundary

Allow it only for your own templates

Key takeaways

  • A browser renders on its own schedule; smooth, repeatable video requires owning the clock.

  • Cover every time source: JavaScript timers and rAF, CSS and Web Animations, and media elements.

  • Stream PNG frames to ffmpeg through image2pipe and respect backpressure.

  • Encode H.264 with yuv420p and +faststart for broad playback.

  • Test WebGL with production flags; software rendering is opt-in in current Chrome.

References