最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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.

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.

Share Improve this question asked Jun 11, 2015 at 10:12 Gordon DuganGordon Dugan 1292 silver badges6 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

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);
发布评论

评论列表(0)

  1. 暂无评论