Dev.to AI πŸ€– Ai πŸ‘ 0 πŸ“– 4 min read

Deterministic 2D Motion Graphics in the Browser: Canvas 2D, Seeded PRNGs, and WebCodecs MP4 Export

Short-form video editors and SaaS teams frequently need three-to-five-second visual callouts: a kinetic headline lockup, a newspaper marker highlight, a mechanical split-flap board, or a rolling KPI counter. Desktop comp

Deterministic 2D Motion Graphics in the Browser: Canvas 2D, Seeded PRNGs, and WebCodecs MP4 Export

Short-form video editors and SaaS teams frequently need three-to-five-second visual callouts: a kinetic headline lockup, a newspaper marker highlight, a mechanical split-flap board, or a rolling KPI counter. Desktop compositors like After Effects handle those clips well, yet launching a heavy project just to swap one sentence and re-render takes far longer than editing the rest of the video. Cloud generative video models introduce a different problem: diffusion models regularly misspell words, blur thin strokes, and require uploading unreleased scripts to remote queues.

When building MotionClip AI, we took a different route: treat 2D motion graphics as pure deterministic functions of time t rendered directly on an HTML5 <canvas> and encoded locally in the browser with WebCodecs and streaming GIF quantization.

Browser-local Canvas 2D motion studio workbench showing real-time preview and timeline controls

1. Make Every Frame a Pure Function of Normalized Time

The single architectural rule that keeps browser preview and video export pixel-identical is banishing wall-clock time (Date.now() or performance.now()) and Math.random() from rendering code.

Instead, every animation plugin implements one stateless signature:

export interface RenderContext {
  ctx: CanvasRenderingContext2D;
  width: number;
  height: number;
  progress: number; // strictly in [0, 1]
  forExport: boolean;
}

At 60fps over a four-second clip, the exporter computes an exact array of 240 timestamps (i / fps) and invokes renderFrame sequentially. Scrubbing to progress = 0.5 in the editor produces the exact same pixel buffer as frame 120 in the exported MP4.

Deterministic Jitter With a Seeded PRNG

Stop-motion paper cutouts, vintage newspaper camera shake, and human typing cadences rely on organic irregularity. Using Math.random() would cause the preview to look different from the exported clip and make frame scrubbing strobe uncontrollably.

A tiny Mulberry32 seeded PRNG keyed to the quantized frame index solves both problems:

export function createSeededRandom(seed: number): () => number {
  let state = seed >>> 0;
  return () => {
    state = (state + 0x6d2b79f5) >>> 0;
    let t = Math.imul(state ^ (state >>> 15), 1 | state);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

By quantizing stop-motion scenes to 12fps (Math.floor(timeSec * 12)) and feeding that integer into createSeededRandom, torn-paper micro-jitter holds steady for five consecutive 60fps frames before snapping cleanly to the next tactile offset.

2. Guarantee Even Pixel Dimensions Across Aspect Ratios

H.264 encoders (including Chrome and Edge's WebCodecs VideoEncoder with avc1.640028 / avc1.42E01F) reject odd canvas widths or heights with an encoding error. A naive Math.round(height * 16 / 9) calculation often lands on odd numbers at non-standard heights.

Enforcing positive even dimensions inside a shared helper prevents silent encoder failures across 16:9, 9:16, 1:1, and 4:5 layouts:

function toEven(value: number): number {
  const rounded = Math.max(2, Math.round(value));
  return rounded % 2 === 0 ? rounded : rounded + 1;
}

At 480p this guarantees exact pairs like 854x480 (16:9), 480x854 (9:16), 480x480 (1:1), and 480x600 (4:5), while 1080p maps cleanly to 1920x1080, 1080x1920, 1080x1080, and 1080x1350.

3. Encode Locally With WebCodecs MP4 and Streaming GIF

Once frames render deterministically, local encoding breaks into three clean paths depending on target NLE workflow:

  1. H.264 MP4 via WebCodecs + mp4-muxer: Feed each rendered canvas into new VideoFrame(canvas, { timestamp }), encode with VideoEncoder, mux with fastStart: 'in-memory' so the moov atom sits at the start of the file for instant timeline scrubbing, and close every VideoFrame immediately in a finally block to prevent GPU memory exhaustion.
  2. Real-Time WebM Fallback via MediaRecorder: On browsers without VideoEncoder, capture the canvas stream at the target frame rate, guard onerror and premature onstop events so incomplete or zero-byte recordings reject cleanly, and fall back to VP9/VP8 WebM.
  3. Streaming Frame-by-Frame GIF Encoding: Buffering 180 full 1080p RGBA frames in JavaScript consumes over 1.4 GB of RAM and crashes mobile Safari. Streaming quantization with gifenc reads one frame's ImageData, quantizes its 256-color palette, writes the compressed frame bytes to the output stream, and lets GC reclaim the buffer immediately. Peak memory stays under 25 MB.

4. Keep Preview Checkerboards Out of Transparent Exports

Editors frequently layer title cards over footage in CapCut, DaVinci Resolve, or Premiere Pro. In the browser preview, drawing a subtle grey-and-white checkerboard behind transparent artwork helps users see white typography.

That checkerboard must never leak into exported files. Passing forExport: true into the background renderer ensures the export canvas calls ctx.clearRect(0, 0, width, height) for transparent WebM Alpha, PNG, and transparent GIF exports while preserving textured paper or film grain on solid-background clips.

Practical Takeaway

You do not need a GPU render farm to ship crisp, timeline-ready 2D motion graphics. A pure renderFrame(t) contract, seeded frame-quantized randomness, even-dimension guards, and streaming local encoders cover the majority of everyday kinetic typography, paper cutout, and data callout clips directly inside a single browser tab. You can test the full set of nine browser-local studios live at MotionClip AI.

πŸ“° Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.