Skip to content
jshacks.dev
Browser

Show a video thumbnail at a given time

Capture a video frame at a chosen second by setting currentTime, waiting for the seeked event and drawing the frame to a canvas as a thumbnail.

1 min read
Summarize in AI

To show a preview from a video file the user picked, seek to a time and draw that frame on a canvas.

thumbnail.jsJavaScript
function thumbnailAt(file, seconds) {
  return new Promise((resolve, reject) => {
    const video = document.createElement('video');
    video.muted = true;
    video.src = URL.createObjectURL(file);

    video.addEventListener('loadedmetadata', () => {
      video.currentTime = Math.min(seconds, video.duration);
    });

    video.addEventListener('seeked', () => {
      const canvas = document.createElement('canvas');
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;
      canvas.getContext('2d').drawImage(video, 0, 0);
      URL.revokeObjectURL(video.src);
      canvas.toBlob(resolve, 'image/jpeg', 0.8);
    });

    video.addEventListener('error', () => reject(video.error));
  });
}

const blob = await thumbnailAt(document.querySelector('input').files[0], 5);
console.log(blob.type);
Text
image/jpeg

Setting currentTime starts a seek, and seeked fires when the frame for that time is ready, so the draw happens at the right moment. The Math.min keeps the target inside short clips. The canvas takes the video's natural size from videoWidth and videoHeight.

The browser must be able to decode the format, and a cross-origin video without CORS headers taints the canvas so toBlob throws. Seeking to an exact frame is not guaranteed for every codec. See the seeked event.

Share

More snippets

APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read
Browser

Find the closest ancestor with closest

Walk up from an element to the nearest ancestor that matches a selector with closest, which includes the element itself. Works in all modern browsers.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.