Book a call
Menu

Porting a Video Compositor to Canvas 2D: Letterboxing, a Mirrored Camera Crop and a Badge That Stays Readable

Happy Coders team26 Nov 202614 min read
Porting a Video Compositor to Canvas 2D: Letterboxing, a Mirrored Camera Crop and a Badge That Stays Readable

Our screen recorder started life as a Mac app, written in Swift, compositing with Core Image. When we built the Chrome and Edge extension, the recording pipeline had to be rebuilt from scratch around browser APIs, and we wrote about that part separately: how the extension keeps recording when its window is minimised, with insertable streams, a Worker and an OffscreenCanvas. That post is about getting frames in and out. This one is about the other half: what happens to a single frame in the middle.

Each output frame is drawn from up to four things: the captured screen, a camera or logo bubble, an optional line of text the user can add, and a small “Happy Recorder” badge that appears in every recording. Porting that drawing code from Core Image to the Canvas 2D API looked like a mechanical translation. It mostly was. The parts that were not, coordinate systems, a screen that changes size mid-recording, a mirrored camera, a face-tracking crop that wobbled, and text that had to stay readable over any background, are what this post is about. Every snippet is from the shipping extension, trimmed for width.

One pure function per frame

The first decision was structural. The compositor is a single module that only draws. It holds no streams, starts no timers and touches no DOM. The Worker owns the loop and the frames; once per tick it hands the newest screen frame, the newest camera frame and the current settings to one function, and that function paints them in a fixed order:

// One output frame, back to front. Pure drawing: no streams, timers or DOM,
// so the same function runs in the compositor Worker and, if needed, on a window.
export function drawFrame(ctx, width, height, state) {
  const cfg = state.cfg || {};
  ctx.save();
  ctx.setTransform(1, 0, 0, 1, 0, 0);
  ctx.globalAlpha = 1;
  ctx.fillStyle = '#000';
  ctx.fillRect(0, 0, width, height);                       // 1. black
  drawScreen(ctx, width, height, state.screen, cfg.crop);   // 2. screen, letterboxed
  drawBubble(ctx, width, height, cfg.bubble, state);        // 3. camera or logo
  if (cfg.watermark && cfg.watermark.text)
    drawWatermark(ctx, width, height, cfg.watermark);       // 4. the user's own text
  drawBadge(ctx, width, height, cfg.badgeText);             // 5. brand badge, always
  ctx.restore();
}

Keeping the drawing pure paid off three ways. The same code can run inside the Worker on an OffscreenCanvas or on an ordinary canvas in a window, which made it easy to test against a visible canvas. Settings can change mid-recording without the drawing code knowing: the Worker merges a partial config into its state and the next frame simply reads it. And the order of layers is in one place, readable top to bottom, so “the badge is always on top” is a fact about five lines of code rather than a property spread across a render graph.

The save(), setTransform(1, 0, 0, 1, 0, 0) and restore() around the whole frame matter more than they look. The bubble is drawn with a flip transform, and the chips set fonts and alignment. Resetting at the start of every frame means one layer’s leftover state can never leak into the next frame. A canvas that is drawn on thirty times a second for an hour will eventually hit any state leak you leave in.

The five layers drawn for every output frame
Back to front, in one function, every frame.

Coordinates: from bottom-left to top-left

Core Image puts the origin at the bottom-left, with y growing upwards. Canvas puts it at the top-left, with y growing down. Every vertical position in the Swift code had to be flipped. For rectangles placed relative to the frame, such as the bubble in a corner, that is easy to get right, because you think in terms of “top” and “bottom” anyway. The trap is in shapes that were specified as raw numbers, like the brand icon inside the badge, which the Mac app drew from a small table of fractions:

// The Mac drew the icon bottom-up (Core Image, origin bottom-left).
// Canvas is top-down, so every y becomes 1 - macY - macHeight.
// Blue face: Mac rect x 0.365, y 0.505 (from bottom), size 0.27.
ctx.arc(ox + s * (0.365 + 0.135),
        oy + s * (1 - 0.505 - 0.27 + 0.135),
        s * 0.135, 0, Math.PI * 2);

We kept the Mac’s numbers verbatim and wrote the conversion out in each call, rather than pre-computing new constants. It looks clumsy, and it is deliberate: anyone comparing the two codebases can check each value against the Swift file line by line, and the one formula, 1 - y - height, is visible everywhere it is applied. An icon whose smile is upside down is an easy bug to see. An icon whose green dot is three pixels too low is not, and that is what pre-computed constants would have hidden.

The screen: normalised crops and letterboxing

Users can record the whole capture or a region of it. The region is stored as fractions of the source, from 0 to 1, not as pixels. That one choice removes a whole category of bugs. The capture’s real pixel size is not known until frames arrive, it differs between a 1440p display and a 1080p one, and it can change mid-recording. A crop stored in pixels is wrong the moment any of that happens. A crop stored as “the middle 60% across, the top half down” is still right.

function drawScreen(ctx, width, height, screen, crop) {
  const { width: sw, height: sh } = sourceSize(screen);
  if (!(sw > 0 && sh > 0)) return;
  let sx = 0, sy = 0, sWidth = sw, sHeight = sh;
  if (crop && crop.width > 0 && crop.height > 0) {   // crop is 0..1, not pixels
    sx = clamp(crop.x, 0, 1) * sw;
    sy = clamp(crop.y, 0, 1) * sh;
    sWidth  = Math.max(1, Math.min(sw - sx, crop.width  * sw));
    sHeight = Math.max(1, Math.min(sh - sy, crop.height * sh));
  }
  // FIT, never stretch: a resolution change mid-recording letterboxes.
  const scale = Math.min(width / sWidth, height / sHeight);
  const dw = sWidth * scale, dh = sHeight * scale;
  try {
    ctx.drawImage(screen, sx, sy, sWidth, sHeight,
                  (width - dw) / 2, (height - dh) / 2, dw, dh);
  } catch {
    // The frame was closed between being picked up and drawn; skip it.
  }
}

The comment in the middle is the important rule: fit, never stretch. The output canvas size is fixed when the recording starts. It comes from the capture size, capped by the quality setting. But the source can change size while recording: the user resizes the window being captured, switches what they are sharing, or moves it to another display. With a stretch, a window dragged narrower would squash everything in the video. With a fit, the picture keeps its shape and black bars fill the difference, which is what every video player does and what viewers expect.

The black fill at the start of drawFrame is what makes the bars black, and it also covers a subtler case. A frame that arrives already closed, because the capture pool reclaimed it between being picked up and being drawn, makes drawImage throw. We catch that and skip the screen for that one frame. Without the black fill, the previous frame’s pixels would still be on the canvas. With it, the worst case is a single black frame, which nobody can see at thirty frames a second.

Finding the source size needed its own small helper, because drawImage accepts several types and each reports its size under a different name:

/// drawImage accepts several source types, and each reports its size differently.
export function sourceSize(src) {
  if (!src) return { width: 0, height: 0 };
  if (typeof src.displayWidth === 'number')          // VideoFrame
    return { width: src.displayWidth, height: src.displayHeight };
  if (typeof src.videoWidth === 'number')            // <video>
    return { width: src.videoWidth, height: src.videoHeight };
  return { width: src.width || 0, height: src.height || 0 };  // ImageBitmap, canvas
}

A VideoFrame has displayWidth, a video element has videoWidth, and a bitmap has width. Reading the wrong one returns undefined, every calculation becomes NaN, and the canvas silently draws nothing. The guard on the first line of each draw function, return unless both sizes are positive, turns that from a blank recording into a skipped layer.

The camera bubble: mirrored, zoomed and steady

The bubble is a circle or a rounded card in one corner, sized as a fraction of the frame height: 18%, 24% or 34% for small, medium and large, with the card 1.5 times as wide as it is tall. Its position is a margin of 3.5% from the side and 4.5% from the top or bottom. Everything is relative, so the bubble looks the same in a 720p recording and a 4K one.

The camera image inside it is where the subtle work is. People expect their own camera preview to behave like a mirror: raise your right hand and the hand on the right of the preview goes up. So the preview is mirrored, and so is the recording, because a bubble that flips the moment you press Record looks like a bug. The crop is calculated in mirrored coordinates, the same space as the preview the user lined themselves up in, and converted back only at the moment of drawing:

// The crop is worked out in mirrored camera coordinates (what the user saw
// in the preview). Convert back to the source, then draw flipped.
const sx = camW - crop.x - crop.width;
ctx.translate(rect.x + rect.width, rect.y);
ctx.scale(-1, 1);
ctx.drawImage(src, sx, crop.y, crop.width, crop.height,
              0, 0, rect.width, rect.height);

Doing all the maths in one coordinate space and converting once, at the last line, is far easier to reason about than flipping every intermediate value. When the face-focus option is on, the face position arrives unmirrored from the detector, so it is converted into mirrored space on the way in, once, and nowhere else.

Following a face without seasickness

Face focus zooms the bubble and keeps it centred on the person’s face. In the Mac app, Apple’s Vision framework provides the face position. In the browser, the extension uses the FaceDetector API where the browser offers it, and quietly does without it where it does not:

// Every 8th tick, on a clone, so the pump can close the original meanwhile.
clone = frame.clone();
const faces = await detector.detect(clone);
const box = faces && faces[0] && faces[0].boundingBox;
if (box) {
  const next = { x: box.x / w, y: box.y / h, width: box.width / w, height: box.height / h };
  state.face = prev ? {
    x: lerp(prev.x, next.x, 0.35), y: lerp(prev.y, next.y, 0.35),
    width: lerp(prev.width, next.width, 0.35), height: lerp(prev.height, next.height, 0.35),
  } : next;
}
// No face this pass: keep the last box. Any error: disable detection for
// the session and fall back to a centred crop.

Three details make this usable. Detection runs only on every eighth tick, because a face does not move far in a quarter of a second, and detection is the most expensive thing in the loop. It runs on a clone of the camera frame, because the pump that feeds the Worker closes old frames as soon as newer ones arrive, and detection is asynchronous. And each new position is blended 35% of the way towards the last one, the same smoothing factor the Swift face tracker uses, so the crop glides instead of snapping.

That was not enough. Even smoothed, a detector reports a slightly different box on every pass, and a crop that follows every one of those changes produces a bubble that shimmers. The fix was a dead-zone: if the new crop would move less than 4% of the camera width or height, and change size by less than 2%, keep the old one exactly.

// Hold the previous crop for sub-4% movements and sub-2% size changes,
// so the recorded bubble does not jitter with every tracking tick.
if (last.valid && last.camW === camW && last.camH === camH
    && Math.abs((last.x + last.width / 2)  - cx) < camW * 0.04
    && Math.abs((last.y + last.height / 2) - cy) < camH * 0.04
    && Math.abs(last.width  - cropW) < camW * 0.02
    && Math.abs(last.height - cropH) < camH * 0.02) {
  rect = { x: last.x, y: last.y, width: last.width, height: last.height };
} else {
  Object.assign(last, rect, { camW, camH, valid: true });
}

The dead-zone state lives in an object the Worker passes in on every frame, so the compositor itself stays stateless. When the user changes the bubble’s shape, size or corner, or the crop, mid-recording, the Worker resets that object. Otherwise a deliberate change smaller than the dead-zone could be swallowed by it. A rule that exists to ignore noise has to be told when a change is not noise.

Problems porting the camera bubble and how each was solved
Each fix lives in one place in the code.

Text that stays readable over anything

Two text chips can appear on a frame. One is the user’s own watermark, such as a company name or “Draft, do not share”, which is off by default and can go in three corners. The other is the “Happy Recorder” badge with the app’s icon, top-right, in every recording. The badge is how a free recorder with no account and no paid tier tells viewers where the video came from, and it is the reason the watermark can never take the top-right corner.

Text over video has a well-known problem: the video behind it changes. White text with a shadow is readable over a dark editor and lost over a white document. A semi-transparent background is readable most of the time, which in a ten-minute recording means unreadable for some of it. We chose a solid black pill behind both chips:

function chipMetrics(ctx, width, height, text, withIcon) {
  const fontSize = Math.max(12, height * 0.011);   // scales with output, never below 12px
  const textHeight = fontSize * 1.25;
  const font = `600 ${fontSize}px ${CHIP_FONT_FAMILY}`;
  const textWidth = measureText(ctx, font, text);   // cached: same text every frame
  /* ... padding, icon size, margins as fractions of the frame ... */
}

function fillChip(ctx, x, y, m) {
  // Solid black pill: the video behind can never affect legibility.
  ctx.fillStyle = '#000';
  ctx.fill(roundedRect(new Path2D(), x, y, m.width, m.height, m.height / 2));
}

The font size scales with the output height, 1.1% of it, but never drops below 12 pixels, so the badge stays proportionate in a 4K recording and legible in a small one. Margins are fractions of the frame for the same reason.

The measureText cache looks like premature optimisation, and in most code it would be. Here the same one or two strings are measured on every frame, thirty or sixty times a second, for as long as the recording runs. Text measurement is not free, and the answer never changes for the same font and text. The cache is keyed on both, and cleared if it ever grows past 64 entries, which only happens if someone edits the watermark text repeatedly during a recording.

Frame timing belongs to the Worker

The compositor draws; the Worker decides when. It runs a timer at the chosen frame rate, between 1 and 60, and on each tick it draws only if a screen frame has arrived and the previous output frame has been accepted downstream. If the encoder is still busy with the last frame, the tick is skipped rather than queued. The output’s timestamps are taken from the clock in microseconds, and forced to increase by at least one on every frame, because two frames with the same timestamp confuse an encoder in ways that are hard to diagnose later.

A skipped tick is a dropped frame in the recording. That is the right trade. A recorder that queues frames it cannot encode falls further and further behind and eventually runs out of memory; one that drops a frame under load produces a recording that is very slightly less smooth for a moment. The previous post covers this loop in more detail.

What we would do the same way again

  • Keep the drawing pure. One function, sources and settings in, pixels out. The loop, the frames and the timing live elsewhere.
  • Reset canvas state at the start of every frame. A transform or font left over from one layer must never reach the next frame.
  • Store geometry as fractions. Crops, bubble sizes, margins and font sizes all survive a change of resolution.
  • Fit, never stretch, and paint the background first, so a missing or resized source degrades into black bars, not distortion or stale pixels.
  • Do the maths in one coordinate space and convert once, at the point of drawing, whether the conversion is a mirror or a y-flip.
  • Smooth, then add a dead-zone, and reset the dead-zone on deliberate changes.
  • Put text on a solid background if it has to be readable over arbitrary video.

Questions we were asked

Why Canvas 2D and not WebGL?

Every operation here is a scaled image copy, a clip, or a filled shape, and the 2D context does all of them with hardware acceleration in Chrome and Edge. WebGL would have meant writing shaders for a rounded clip and text rendering, for no measurable gain at these frame rates.

Can the badge be turned off?

No. It is small, it sits in one corner, and it is the one thing we ask in return for a recorder with no account, no time limit and no paid tier. The user’s own watermark text is separate and entirely optional.

Does face focus send the camera anywhere?

No. Detection runs in the browser on the local frame. If the browser does not offer the face detection API, the option simply falls back to a centred crop.

HappyRec is our free screen recorder for Mac, Windows, Chrome and Edge. We also build browser extensions and media-heavy web apps for clients in the US, Singapore and worldwide. See HappyRec.

Keep reading

Related articles