如何使用javascript获取html5视频的缩略图

How can I use javascript to get the thumbnail of an html5 video?

本文关键字:略图 视频 html5 何使用 javascript 获取      更新时间:2023-09-26

我找到了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);