Dev.to WebDev πŸ›  Dev πŸ‘ 2 πŸ“– 9 min read

Build a Zero-Upload 9:16 Video Clipper with Canvas and MediaRecorder

Suppose you have a 16:9 interview and know the exact moment you want to cut. To turn it into a vertical clip, you need three things: the source timestamps, a crop that keeps the speaker in frame, and an encoder that can

Suppose you have a 16:9 interview and know the exact moment you want to cut. To turn it into a vertical clip, you need three things: the source timestamps, a crop that keeps the speaker in frame, and an encoder that can save what you see.

The browser already gives you those pieces. Load the file with a blob URL, seek a video element to the in-point, draw a 9:16 rectangle into a canvas as the video plays, then record that canvas with MediaRecorder. The file stays on the device because the demo has no upload or network code.

Why Canvas and MediaRecorder are enough for this job

The multithreaded ffmpeg.wasm core needs SharedArrayBuffer, which browsers normally expose to web pages in a secure, cross-origin-isolated context. On a self-hosted page that typically means configuring COOP and COEP response headers and making sure your cross-origin resources meet the embedding rules. ffmpeg.wasm also has a single-threaded core. The Canvas and MediaRecorder path below has no shared-memory dependency, so it can run without those isolation headers. ffmpeg.wasm usage docs Β· Cross-origin isolation guide

The trade-off is timing. This is a real-time playback-and-record pipeline for short clips. It decodes the input and re-encodes the cropped frames. Its trim points are approximate, and an export typically takes roughly as long as the selected range, plus setup and finalization.

1. Set up the source and the vertical preview

Create an index.html file with the markup below. Paste the JavaScript in the next section inside the <script> block at the bottom. Open the page in a browser and pick a local video longer than the chosen out-point. Keep the tab visible while exporting. The example records video only, with a 540 Γ— 960 canvas and a target of up to 30 draw updates per second.

<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Local vertical clipper</title>

<label>Video <input id="file" type="file" accept="video/*"></label>
<label>In (s) <input id="in" type="number" min="0" step="0.1" value="1"></label>
<label>Out (s) <input id="out" type="number" min="0" step="0.1" value="5"></label>
<label>Horizontal framing
  <input id="focus" type="range" min="0" max="1" step="0.01" value="0.5">
</label>
<button id="export" type="button">Export clip</button>
<a id="download" hidden>Download clip</a>
<p id="status" role="status"></p>
<video id="source" muted playsinline style="width:min(100%,360px)"></video>
<canvas id="preview" width="540" height="960"
        style="width:min(100%,270px);height:auto"></canvas>

<script>
  // Paste the JavaScript here.
</script>

For a 1920 Γ— 1080 source, the crop covers the full height and about 608 source pixels of width. The slider moves that rectangle from the left edge to the right edge. For a source narrower than 9:16, the code takes the full width and centers the crop vertically. The nine-argument form of drawImage() maps that source rectangle onto the entire destination canvas. HTML canvas drawing spec

2. Seek, draw, and record

Wait for metadata before reading the duration and dimensions. After assigning currentTime, wait for the seek to settle before painting the first frame. Create the recorder from the canvas stream, redraw that first frame after the recorder starts, and let the source play at normal speed. Stop when the video clock reaches the out-point. Save the blob after the recorder delivers its final chunks and fires stop. HTML media spec Β· MediaStream Recording spec

const byId = id => document.getElementById(id);
const video = byId("source");
const canvas = byId("preview");
const ctx = canvas.getContext("2d", { alpha: false, willReadFrequently: true });
const button = byId("export");
const download = byId("download");
const status = byId("status");
let downloadUrl;

function waitForMedia(eventName, action) {
  return new Promise((resolve, reject) => {
    const listeners = new AbortController();
    const options = { signal: listeners.signal };
    const timer = setTimeout(() => {
      finish(new Error("Timed out while loading or seeking the source."));
    }, 15000);

    function finish(error) {
      clearTimeout(timer);
      listeners.abort();
      if (error) reject(error);
      else resolve();
    }

    video.addEventListener(eventName, () => finish(), options);
    video.addEventListener("error", () => {
      finish(new Error("The browser could not decode this video."));
    }, options);

    try {
      action?.();
    } catch (error) {
      finish(error);
    }
  });
}

function makeCrop(focus) {
  const ratio = canvas.width / canvas.height;
  const width = Math.min(video.videoWidth, video.videoHeight * ratio);
  const height = width / ratio;
  const x = (video.videoWidth - width) * focus;
  const y = (video.videoHeight - height) / 2;

  return () => {
    ctx.drawImage(video, x, y, width, height, 0, 0, canvas.width, canvas.height);
  };
}

async function recordRange(start, end, draw) {
  const stream = canvas.captureStream();
  const listeners = new AbortController();
  const options = { signal: listeners.signal };
  let recorder;
  let frameId;
  let deadline;

  try {
    const candidates = ["video/webm;codecs=vp8", "video/mp4", "video/webm"];
    const mimeType = candidates.find(type => MediaRecorder.isTypeSupported(type));
    recorder = new MediaRecorder(stream, mimeType ? { mimeType } : undefined);

    return await new Promise((resolve, reject) => {
      const chunks = [];
      const frameMs = 1000 / 30;
      let nextDraw = 0;

      function stop() {
        video.pause();
        cancelAnimationFrame(frameId);
        if (recorder.state === "recording") recorder.stop();
      }

      function tick(now) {
        if (video.currentTime >= end || video.ended) {
          stop();
          return;
        }

        if (now >= nextDraw && video.readyState >= HTMLMediaElement.HAVE_CURRENT_DATA) {
          try {
            draw();
          } catch (error) {
            reject(error);
            return;
          }
          const slots = Math.floor((now - nextDraw) / frameMs) + 1;
          nextDraw += slots * frameMs;
        }

        frameId = requestAnimationFrame(tick);
      }

      recorder.addEventListener("dataavailable", event => {
        if (event.data.size) chunks.push(event.data);
      }, options);
      recorder.addEventListener("stop", () => {
        if (!chunks.length) {
          reject(new Error("The browser returned an empty recording."));
          return;
        }
        resolve(new Blob(chunks, { type: chunks[0].type || recorder.mimeType }));
      }, options);
      recorder.addEventListener("error", event => {
        reject(event.error || new Error("Recording failed."));
      }, options);
      video.addEventListener("ended", stop, options);
      video.addEventListener("error", () => {
        reject(new Error("The source stopped decoding."));
      }, options);
      document.addEventListener("visibilitychange", () => {
        if (document.hidden) reject(new Error("Keep this tab visible while exporting."));
      }, options);

      deadline = setTimeout(() => {
        reject(new Error("Playback or recording stalled."));
      }, (end - start + 10) * 1000);

      recorder.start();
      draw();
      video.play().then(() => {
        if (listeners.signal.aborted) return;
        nextDraw = performance.now();
        frameId = requestAnimationFrame(tick);
      }, reject);
    });
  } finally {
    clearTimeout(deadline);
    cancelAnimationFrame(frameId);
    listeners.abort();
    video.pause();
    if (recorder?.state === "recording") recorder.stop();
    stream.getTracks().forEach(track => track.stop());
  }
}

button.addEventListener("click", async () => {
  const file = byId("file").files[0];
  if (!file) {
    status.textContent = "Choose a local video first.";
    return;
  }

  button.disabled = true;
  const sourceUrl = URL.createObjectURL(file);

  try {
    if (!ctx || !canvas.captureStream || !window.MediaRecorder) {
      throw new Error("This browser lacks Canvas capture or MediaRecorder.");
    }

    status.textContent = "Loading the video…";
    await waitForMedia("loadedmetadata", () => { video.src = sourceUrl; });

    const start = byId("in").valueAsNumber;
    const end = byId("out").valueAsNumber;
    if (!video.videoWidth || !Number.isFinite(video.duration) ||
        !Number.isFinite(start) || !Number.isFinite(end) ||
        start < 0 || end <= start || end > video.duration) {
      throw new Error("Choose a video and a valid range within its duration.");
    }

    if (video.currentTime !== start) {
      await waitForMedia("seeked", () => { video.currentTime = start; });
    }
    if (video.readyState < HTMLMediaElement.HAVE_CURRENT_DATA) {
      await waitForMedia("loadeddata");
    }

    status.textContent = "Recording in real time…";
    const blob = await recordRange(start, end, makeCrop(byId("focus").valueAsNumber));
    const extension = { "video/mp4": "mp4", "video/webm": "webm" }[blob.type.split(";")[0]];
    if (!extension) throw new Error("Unexpected recording format: " + blob.type);

    if (downloadUrl) URL.revokeObjectURL(downloadUrl);
    downloadUrl = URL.createObjectURL(blob);
    download.href = downloadUrl;
    download.download = "clip." + extension;
    download.hidden = false;
    status.textContent = "Clip ready.";
  } catch (error) {
    status.textContent = error.message;
  } finally {
    video.removeAttribute("src");
    video.load();
    URL.revokeObjectURL(sourceUrl);
    button.disabled = false;
  }
});

Input and output format support are separate. A browser might decode a file but lack the encoder you want. The demo probes likely recording types with isTypeSupported() and uses the actual MIME type for the download extension. A successful probe is still only a capability signal. Recorder construction or encoding can fail. Test the actual download on your target devices, including representative phone videos. MediaStream Recording spec

3. Keep the clip on time when frames arrive unevenly

A 24 fps source has fewer unique pictures than a 30 Hz draw schedule. On some draw ticks the video is still showing the previous frame, so drawing it again naturally holds that picture. Under load, a draw callback can also run late. In that case, the code advances past the elapsed draw slots and samples the latest available picture once. It never runs a burst of draws to catch up. A burst can paint the same pixels repeatedly and still leave the original timing gap.

The two clocks serve different purposes. video.currentTime decides when the clip ends. The animation callback timestamp controls how often you attempt a canvas update. Canvas capture and MediaRecorder then make their own decisions about which frames get recorded and how they are timed. The browser can produce a variable-frame-rate file even with that 30 Hz draw budget. Repeating a held frame preserves continuity where the browser captures it. Recovering an image that was never sampled requires access to the underlying decoded frames. Canvas capture spec

In a Windows headless Chrome test, the file had a gap in its video packet timestamps while the source continued to deliver video frame callbacks. The gap disappeared in a diagnostic run with the browser's GPU path disabled. The example's willReadFrequently hint can favor a software-backed 2D canvas, though gaps still occurred in some test runs with that hint enabled. If a similar issue shows up, compare the source callback times and the file's packet times before tuning the draw loop. HTML canvas context settings

To diagnose stutter, register requestVideoFrameCallback() on the source video when the API is available. Log each callback's mediaTime and the change in presentedFrames. A jump in that counter means you missed one or more compositor submissions between callbacks. That counter describes the source compositor. Inspect the exported file separately to measure recording gaps. For example, ffprobe -v error -select_streams v:0 -show_entries packet=pts_time -of csv=p=0 clip.webm prints the video packet timestamps. Compare consecutive values to locate long holds. If ordinary exports stutter, try a smaller canvas or a lower draw cadence and compare the result. Video frame callback explainer

For an exact frame rate or frame-accurate cuts, use a pipeline where you own the frames and timestamps. For example, with WebCodecs you would demux the input, decode the selected frames, assign a timestamp to each output frame, and mux the encoded output. If you need a constant rate, that is where you can repeat a frame with an explicit new timestamp. requestFrame() on a canvas capture track can request a sample, but it cannot assign that sample a timestamp. WebCodecs spec Β· Canvas capture spec

Adding audio

Canvas captures pixels. To keep the source audio, use a Web Audio graph that routes the video element through a MediaElementAudioSourceNode into a MediaStreamAudioDestinationNode. Add that destination's audio track to the canvas stream before constructing the recorder. Resume the audio context from a user gesture. Unmute the media element for the audio path and route the graph only to the stream destination for a quiet export. Choose a MIME type that supports both tracks, and check lip sync and both trim points in the exported file. Web Audio spec

Start with two clips, one with an off-center subject and one with fast motion. On the first, check the two slider extremes and verify the output dimensions. On the second, compare playback at different canvas sizes and listen for drift if you add audio. It's worth testing an in-point of zero and a second export in the same tab as well.

For a visual reference, the FreeClipping editor shows how a timeline and draggable crop frame can expose the in-point, out-point, and framing controls to users.

AI assisted with drafting this tutorial.

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

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