问题
I have found the JavaScript code to get the thumbnail of a video, given its URL. However, I've only found this for YouTube and Vimeo. Nobody seems to have listed an example of how to do it with video that is intended to be embedded with the html5 video tag. Can it be done? Thanks.
回答1:
Yes, you can use video as image source for canvas. Just wrap the code as a function which takes video and size as arguments, and return a canvas element.
The video must be loaded and at the frame you want to snapshot.
Example methods
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 DOM and used as the image holder. If you prefer an image element you would have to do a couple of more steps, as well as handle the asynchronous nature of image loading using 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 get problems with the size of the video frame, you can replace the drawImage() arguments with this:
ctx.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, w, h);
来源:https://stackoverflow.com/questions/30777915/how-can-i-use-javascript-to-get-the-thumbnail-of-an-html5-video