我找到了获取视频缩略图的 JavaScript 代码,给出了它的 URL。但是,我只为 YouTube 和 Vimeo 找到了这个。似乎没有人列出如何处理旨在嵌入 html5 视频标签的视频的示例。可以做到吗?谢谢。
问问题
6614 次
1 回答
6
是的,您可以使用视频作为画布的图像源。只需将代码包装为一个以视频和大小为参数的函数,然后返回一个画布元素。
视频必须加载并位于您要拍摄快照的帧处。
示例方法
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);
于 2015-06-12T03:20:33.627 回答