Building a screen recorder in the browser sounds simple at first: just call getDisplayMedia() and feed it into a MediaRecorder.
But if you want to create a screen studio — with webcam overlays, custom backgrounds, and zero-latency UI — the complexity ramps up fast. This is the architecture behind Gravity Recorder, built entirely with React, the Canvas API, and a handful of modern browser APIs that most developers have never touched.
The Challenge: Compositing in Real-Time
A standard MediaRecorder takes a single stream. To have a screen and a webcam, you usually have to choose one or use CSS to overlay them. But if you want to record the combination as a single video file, you need to composite them.
Step 1: Capturing the Streams
We start by capturing the system audio, screen, and mic/webcam separately:
const screenStream = await navigator.mediaDevices.getDisplayMedia({
video: { width: 2560, height: 1440 },
audio: true
});
const cameraStream = await navigator.mediaDevices.getUserMedia({
video: true,
audio: true
});
Step 2: The Canvas Engine
This is where the magic happens. We don't record the streams directly. Instead, we create a high-resolution <canvas> element and run a render loop at 60fps.
In each frame, we draw:
- The background (gradient or custom image)
- The screen capture (scaled and padded with letterboxing)
- The webcam (masked as a circle or rounded rect)
function renderFrame() {
ctx.drawImage(bgImage, 0, 0, 1920, 1080);
ctx.drawImage(screenVideo, screenX, screenY, screenW, screenH);
// Camera bubble with circular mask
ctx.save();
ctx.beginPath();
ctx.arc(camX, camY, radius, 0, Math.PI * 2);
ctx.clip();
ctx.drawImage(cameraVideo, camX - radius, camY - radius, radius * 2, radius * 2);
ctx.restore();
// NOTE: see the performance section below — Gravity does not actually drive
// this with requestAnimationFrame, because rAF stops firing in a background
// tab and a screen recorder is backgrounded almost the entire time.
requestAnimationFrame(renderFrame);
}
We then capture the canvas as a stream and hand it to MediaRecorder:
const canvasStream = canvas.captureStream(30);
// Audio is added separately (see below)
const recorder = new MediaRecorder(canvasStream, {
mimeType: 'video/webm;codecs=vp9',
videoBitsPerSecond: 8_000_000
});
Mixing Audio Tracks
Getting clean audio out of a composited recording is harder than it looks. You have two audio sources — system audio from getDisplayMedia and microphone audio from getUserMedia — and you need to merge them into a single track before passing it to the recorder.
The Web Audio API's AudioContext handles this cleanly:
const audioCtx = new AudioContext();
const systemSource = audioCtx.createMediaStreamSource(
new MediaStream(screenStream.getAudioTracks())
);
const micSource = audioCtx.createMediaStreamSource(
new MediaStream(cameraStream.getAudioTracks())
);
const destination = audioCtx.createMediaStreamDestination();
systemSource.connect(destination);
micSource.connect(destination);
// destination.stream is a single mixed audio track
const mixedAudioTrack = destination.stream.getAudioTracks()[0];
You then add mixedAudioTrack to the canvas stream before creating the MediaRecorder. The result is a single video file with both the system and mic audio properly balanced.
A common mistake here is connecting micSource directly to audioCtx.destination (the speaker) — that routes audio back out of the speakers and causes an echo loop. Always connect to a MediaStreamDestination, not the playback destination.
Saving Directly to Disk with the File System Access API
Most screen recorder tutorials end with a Blob URL download — the file pops into your Downloads folder and you have to move it manually. Gravity uses the File System Access API to write recordings directly into whatever folder you choose, behaving like a native app.
You ask for a directory once, then write into it whenever you like:
// Ask the user to pick a workspace folder once, upfront
const dirHandle = await window.showDirectoryPicker({ mode: 'readwrite' });
// ...later, when the recording is finished
const fileHandle = await dirHandle.getFileHandle(fileName, { create: true });
const writable = await fileHandle.createWritable();
await writable.write(blob);
await writable.close();
Worth being honest about the trade-off here, because most tutorials gloss over it. Gravity currently collects ondataavailable chunks in an in-memory array and assembles the Blob when recording stops, then writes that file. That is simple and reliable, but it means peak memory scales with recording length.
The alternative is to hold the writable stream open for the whole session and write() each chunk as it arrives. That keeps RAM flat no matter how long you record, and leaves a partially written file on disk if the browser crashes. It is the better design for long recordings, and it is a known piece of work rather than something already shipped.
For browser compatibility, the File System Access API is supported in Chromium browsers such as Chrome, Edge, Brave and Arc. Firefox and Safari do not implement showSaveFilePicker. Gravity Recorder targets desktop Chromium only, because direct-to-folder saving is central to how it works.
Multi-Segment Editing with FFmpeg WebAssembly
Once a recording is saved, users often want to trim the beginning and end or cut out a section in the middle. Running FFmpeg in the browser via WebAssembly makes this possible without any server upload.
Stream copy mode (-c copy) is near-instant because it does not re-encode. But there is a trap here that most tutorials repeat, and it is worth understanding before you ship it.
The obvious command for a simple trim looks like this:
// DON'T do this — it desynchronises audio from video
await ffmpeg.exec([
'-i', 'input.webm',
'-ss', String(startSec),
'-to', String(endSec),
'-c', 'copy',
'output.webm'
]);
Stream copy cannot cut video anywhere except a keyframe, because a mid-GOP frame is meaningless without the keyframe it depends on. Audio has no such constraint and gets cut at the exact sample you asked for. So the two streams begin at different points in the source, and stay offset for the whole clip.
This is easy to measure. On a 20 second test clip with keyframes every 5 seconds, cutting at 7.0s produced a file whose first video packet was at 3.000s and whose first audio packet was at 0.014s. Roughly three seconds of drift, on a cut that looked perfectly reasonable in the code.
The fix is to use the concat demuxer for every cut, single-segment or not. Its inpoint/outpoint rebases both streams together so they stay aligned:
ffconcat version 1.0
file 'input.webm'
inpoint 0
outpoint 12.4
file 'input.webm'
inpoint 31.8
outpoint 95.0
Then pass it to FFmpeg:
await ffmpeg.exec([
'-f', 'concat',
'-safe', '0',
'-i', 'list.txt',
'-c', 'copy',
'output.webm'
]);
The entire operation runs in the browser with no upload, typically completing in a few seconds for a 10-minute recording.
The remaining trade-off is honest to state: because the cut still lands on a keyframe, the result can begin up to one keyframe interval earlier than you asked for. That same 20 second clip returns 10 seconds for an 8 second selection. The end point is exact; only the start is generous. Getting both exact would require re-encoding, which under WebAssembly can take longer than the recording itself — and a cut that starts slightly early is a far smaller problem than audio drifting seconds out of sync.
Optimizing for Performance
Running a 60fps canvas render loop while simultaneously encoding video is CPU-intensive. A few things that make a real difference:
Unified stream capture. canvas.captureStream(30) gives you a single video track of the composited studio, so the MediaRecorder only has to encode one stream.
Don't drive the loop with requestAnimationFrame. This is the one that matters most, and it is counter-intuitive. rAF is tied to the browser's paint cycle, and a hidden tab is never painted — so rAF stops firing entirely when the tab is backgrounded. For a screen recorder the tab is backgrounded almost the whole time you are recording, which would freeze the canvas while audio kept going. setInterval on the main thread is no better: Chrome clamps background timers to roughly once a second.
Gravity drives the render loop from a Web Worker heartbeat instead. Worker timers are not throttled, so the worker posts a tick and the main thread paints a frame in response.
Pace the loop, but don't quantize it. Once you have a worker driving frames, you need back-pressure: if a frame overruns its budget, ticks queue up faster than they can be consumed and the backlog grows without bound. The obvious fix — setInterval plus "skip a beat if the last frame hasn't finished" — is a trap. It pins every tick to an interval boundary, so a 40ms frame misses the 33ms slot and waits until 66ms. That turns 25fps into 15fps. The fix is to self-schedule and fire immediately when a frame is already overdue, so pacing can only prevent a backlog, never slow the loop below what the main thread can actually sustain.
Constrain the capture resolution. getDisplayMedia hands you the display's native resolution unless you ask otherwise. On a Retina screen that is roughly 3000x2000, and if your canvas is 1080p you are paying for a full downscale on every single frame. Profiling Gravity's render loop showed that one drawImage call eating 19ms of a 33ms budget — about 60% of the frame time — while the visual effects everyone assumes are expensive (the glow ring) cost 1.3ms. Applying a track constraint moves that downscale into the browser's own capture pipeline.
Canvas work is deferred, so you cannot profile it by timing the calls. Wrapping drawImage in performance.now() reports approximately zero, because the work has only been queued. You need to force a rasterization flush — a one-pixel getImageData will do it — before the numbers mean anything. Every measurement is worthless until you do.
Lessons Learned
Building Gravity Recorder taught us that the web platform is incredibly capable if you are willing to go beyond the default APIs. The combination of Canvas compositing, the Web Audio API, the File System Access API, and FFmpeg WASM covers most of what native screen recording apps do — without requiring a single install.
The parts that pushed hardest against browser limits were memory during long recordings and the render loop itself. MediaRecorder muxes both tracks live as they arrive rather than at stop, so a video frame that misses its slot is lost permanently — which is why the pacing details above matter more than they look. Audio runs on its own real-time thread and stays accurate on its own; measured across a four-minute recording, video ran 65ms longer than audio, which is inaudible.
If you want to see this architecture running in production, the full source is open on GitHub.
Check out the Source Code on GitHub →
Frequently Asked Questions
Can I build a screen recorder without a Chrome extension?
Yes. navigator.mediaDevices.getDisplayMedia() is a native browser API available in Chrome, Firefox, Edge, and Safari — no extension required. Extensions add overhead and require user permission grants through the Chrome Web Store. A pure web app approach is simpler for users and more portable across browsers.
Does the File System Access API work in Firefox?
No, not for writing files. As of 2026 Firefox does not support showSaveFilePicker. If you are building your own recorder, you can fall back to the traditional Blob → Object URL → anchor download pattern, which puts the file in the Downloads folder instead of a chosen location. Gravity Recorder itself does not take that route and supports desktop Chromium browsers only.
How do I handle the case where the user denies screen capture permission?
getDisplayMedia() throws a NotAllowedError if the user cancels or denies. Wrap it in a try/catch and show an appropriate message — don't silently fail. In Chrome, if the user has previously blocked screen capture at the browser level, you'll also need to guide them to chrome://settings/content/camera to reset it.
What video codec should I use for web recordings?
video/webm;codecs=vp9 is a good baseline — it's widely supported, has good compression, and is the codec most MediaRecorder implementations default to. If you need broader compatibility (particularly for Apple platforms), use video/mp4;codecs=h264 — but check MediaRecorder.isTypeSupported() at runtime since support varies. Gravity Recorder offers MP4 (H.264), WebM and MKV, plus MP3 for audio-only.
Can I record audio-only with this approach?
Yes. Skip the canvas entirely, merge your audio sources via AudioContext as described above, and pass the MediaStreamDestination stream directly to MediaRecorder. Set mimeType: 'audio/webm;codecs=opus' for a high-quality audio-only recording — useful for podcast-style content.
