How can I use javascript to get the html5 video thumbnail?
1 answer
Yes, you can use video as an image source for your canvas. Just wrap the code as a function that takes video and size as arguments and returns a canvas element.
The video must be uploaded and in the frame you want to take a photo.
Method examples
function createThumb(video, w, h) {
var c = document.createElement("canvas"), // create a canvas
ctx = c.getContext("2d"); // get context
c.width = w; // set size = thumb
c.height = h;
ctx.drawImage(video, 0, 0, w, h); // draw in frame
return c; // return canvas
}
The canvas can be inserted into the DOM and used as an image holder. If you prefer an image element, there are a few more steps you will need to follow and also handle the asynchronous nature of image loading with a callback (or promise):
function createThumb(video, w, h, callback) {
var c = document.createElement("canvas"), // create a canvas
ctx = c.getContext("2d"), // get context
img = new Image(); // final image
c.width = w; // set size = thumb
c.height = h;
ctx.drawImage(video, 0, 0, w, h); // draw in frame
img.onload = function() { // handle async loading
callback(this); // provide image to callback
};
img.src = c.toDataURL(); // convert canvas to URL
}
If you are having problems with the video frame size, you can replace the drawImage () arguments like this:
ctx.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, w, h);
+4
source to share