Skip to content

Instantly share code, notes, and snippets.

@arn4v
Created December 30, 2022 21:21
Show Gist options
  • Save arn4v/16139b56010bc6463b1476b9601fe13c to your computer and use it in GitHub Desktop.
Save arn4v/16139b56010bc6463b1476b9601fe13c to your computer and use it in GitHub Desktop.
Get video thumbnails in JS
const getVideoThumbnails = (src: string) => {
let w: number, h: number;
const aspectRatioDivisionMultiple = 2.5;
let screenshotCount = 0;
const screenshots: string[] = [];
const canvas = document.createElement("canvas");
const video = document.createElement("video");
video.autoplay = false;
video.muted = true;
video.src = src;
const ctx = canvas.getContext("2d");
video.addEventListener("loadedmetadata", () => {
const ratio = video.videoWidth / video.videoHeight;
w = video.videoWidth - 100;
h = parseInt(`${w / ratio}`, 10);
canvas.width = w / aspectRatioDivisionMultiple;
canvas.height = h / aspectRatioDivisionMultiple;
video.currentTime = 0.5;
video.play();
});
video.addEventListener("timeupdate", () => {
if (screenshotCount <= 5) {
screenshotCount = ++screenshotCount;
ctx.fillRect(0, 0, w, h);
ctx.drawImage(
video,
0,
0,
w / aspectRatioDivisionMultiple,
h / aspectRatioDivisionMultiple
);
const screenshot = canvas.toDataURL("image/png");
screenshots.push(screenshot);
}
});
video.pause();
return screenshots;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment