Created
December 30, 2022 21:21
-
-
Save arn4v/16139b56010bc6463b1476b9601fe13c to your computer and use it in GitHub Desktop.
Get video thumbnails in JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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