我找到了JavaScript代码来获取视频的缩略图,给定其URL。 但是,我只在YouTube和Vimeo上找到了这个。 似乎没有人列出如何使用打算嵌入html5视频标签的视频的示例。能做到吗?谢谢。
是的,您可以使用视频作为画布的图像源。只需将代码包装为以视频和大小作为参数的函数,并返回一个 canvas 元素。
视频必须加载到要快照的帧。
示例方法
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
}
画布可以插入到 DOM 中并用作图像持有人。如果你更喜欢图像元素,你必须做更多的步骤,以及使用回调(或承诺)处理图像加载的异步性质:
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
}
如果视频帧的大小有问题,可以将 drawImage() 参数替换为以下内容:
ctx.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, w, h);