MDN self-hosted library · e01.org

HTMLVideoElement: requestVideoFrameCallback() method

Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.

js
const button = document.querySelector("button");
const video = document.querySelector("video");
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
const fpsInfo = document.querySelector("#fps-info");
const metadataInfo = document.querySelector("#metadata-info");

button.addEventListener("click", () =>
  video.paused ? video.play() : video.pause(),
);

video.addEventListener("play", () => {
  if (!("requestVideoFrameCallback" in HTMLVideoElement.prototype)) {
    console.error(
      "Your browser does not support the `Video.requestVideoFrameCallback()` API.",
    );
  }
});

let width = canvas.width;
let height = canvas.height;

let startFrames = null;
let startMediaTime = 0;

const resetFps = () => {
  startFrames = null;
};
video.addEventListener("play", resetFps);
video.addEventListener("seeked", resetFps);

const updateCanvas = (now, metadata) => {
  ctx.drawImage(video, 0, 0, width, height);

  if (startFrames === null) {
    startFrames = metadata.presentedFrames;
    startMediaTime = metadata.mediaTime;
  } else {
    const frames = metadata.presentedFrames - startFrames;
    const seconds = metadata.mediaTime - startMediaTime;
    fpsInfo.innerText = seconds > 0 ? (frames / seconds).toFixed(3) : 0;
  }
  metadataInfo.innerText = JSON.stringify(metadata, null, 2);

  video.requestVideoFrameCallback(updateCanvas);
};

video.src = "https://mdn.github.io/shared-assets/videos/flower.mp4";
video.requestVideoFrameCallback(updateCanvas);
css
video,
canvas {
  max-width: 49%;
}
html
<p>
  Start <button type="button">⏯</button> playing the video. Pause the video to
  read the metadata. Drawing video frames on the canvas is synced with the
  actual video framerate.
</p>
<video controls playsinline></video>
<canvas width="960" height="540"></canvas>
<p><span id="fps-info">0</span>fps</p>
<pre id="metadata-info"></pre>