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.
To show a preview from a video file the user picked, seek to a time and draw that frame on a canvas.
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);image/jpegSetting 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.