Skip to content

Instantly share code, notes, and snippets.

@joedf
Last active April 14, 2018 20:32
Show Gist options
  • Save joedf/42e14b35654a5f4e2d482d453c1c449b to your computer and use it in GitHub Desktop.
Save joedf/42e14b35654a5f4e2d482d453c1c449b to your computer and use it in GitHub Desktop.
generate an image from an HTML5 video element, useful for on-the-go thumbnails
// videocapture.js - MIT License
// credits: joedf (2018/04/10)
// Revision 8 - 2018/04/12
// modified from: https://codepen.io/renanpupin/pen/PqjyeK (Renan Pupin)
/**
* Captures a image frame from the provided video element.
*
* @param {Video} video HTML5 video element from where the image frame will be captured.
* @param {Number} scaleFactor Factor to scale the canvas element that will be return. This is an optional parameter.
* @param {Number} square Specify 0 for false, 1 to use width or -1 to use height to make the image forced square with black. This is an optional parameter.
*
* @return {Canvas}
**/
function capture(video, scaleFactor, square) {
if(scaleFactor == null){
scaleFactor = 1;
}
if(square == null){
square = 0;
}
var w = video.videoWidth * scaleFactor;
var h = video.videoHeight * scaleFactor;
var cw = w;
var ch = h;
var cx = 0;
var cy = 0;
if (square > 0) {
ch = w;
cy = ((w-h)/2)>>0;
}
if (square < 0) {
cw = h;
cx = ((h-w)/2)>>0;
}
var canvas = document.createElement('canvas');
canvas.width = cw;
canvas.height = ch;
var ctx = canvas.getContext('2d');
ctx.drawImage(video, cx, cy, w, h);
return canvas;
}
// Helper functions to generate base64 PNG URI, etc.
function capture2png(video, scaleFactor, square) {
var cv = capture(video, scaleFactor, square);
return cv.toDataURL();
}
function capture2jpg(video, scaleFactor, square, quality) {
if(quality == null){
quality = 0.8;
}
var cv = capture(video, scaleFactor, square);
return cv.toDataURL('image/jpeg', quality);
}
//scaling factor helper functions
function captureScaleWidthSize(video, maxWidth) {
return maxWidth / video.videoWidth;
}
function captureScaleHeightSize(video, maxHeight) {
return maxHeight / video.videoHeight;
}
function captureScaleMaxSize(video, maxSize) {
var vmax = Math.Max(video.videoWidth, video.videoHeight);
return maxSize / vmax;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment