Created
September 22, 2024 17:46
-
-
Save imshvc/473812d82c2decf39833c6b3a00e1aad to your computer and use it in GitHub Desktop.
Save frame from video element
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
/** | |
* Save frame from video element | |
* @author Nurudin Imsirovic <[email protected]> | |
* @param {Element} video Video element | |
* @param {boolean} download Download frame as file | |
* @param {string} filename Download name | |
* @return {?string} Blob URL of frame | |
*/ | |
function video2frame(video = null, download = true, filename = null) { | |
// Not a video element | |
if (video instanceof HTMLVideoElement === false) { | |
return null; | |
} | |
// Video dimensions | |
let width = video.videoWidth; | |
let height = video.videoHeight; | |
// Create canvas to draw the frame into | |
let canvas = document.createElement('canvas'); | |
canvas.context = canvas.getContext('2d'); | |
canvas.width = width; | |
canvas.height = height; | |
canvas.context.drawImage(video, 0, 0, width, height); | |
let blob_url = ''; | |
// Create URL for Blob | |
canvas.toBlob(blob => { | |
blob_url = URL.createObjectURL(blob); | |
if (download) { | |
let a = document.createElement('a'); | |
a.href = blob_url; | |
a.download = filename ?? ''; | |
a.click(); | |
a.remove(); | |
} | |
}); | |
return blob_url; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment