Skip to content

Instantly share code, notes, and snippets.

@imshvc
Created September 22, 2024 17:46
Show Gist options
  • Save imshvc/473812d82c2decf39833c6b3a00e1aad to your computer and use it in GitHub Desktop.
Save imshvc/473812d82c2decf39833c6b3a00e1aad to your computer and use it in GitHub Desktop.
Save frame from video element
/**
* Save frame from video element
* @author Nurudin Imsirovic <realnurudinimsirovic@gmail.com>
* @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