如何使用javascript获取html5视频的缩略图? [英] How can I use javascript to get the thumbnail of an html5 video?

查看:112
本文介绍了如何使用javascript获取html5视频的缩略图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经找到了JavaScript代码来获取视频的缩略图(给定了其URL).但是,我只在YouTube和Vimeo上找到了它.似乎没有人列出如何使用打算嵌入html5 video标签的视频的示例.能做到吗谢谢.

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.

推荐答案

是的,您可以将视频用作画布的图像源.只需将代码包装为一个函数,该函数将视频和大小作为参数,然后返回canvas元素.

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.

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并用作图像持有人.如果您更喜欢图像元素,则必须执行更多步骤,并使用回调(或Promise)处理图像加载的异步特性:

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
}

如果您在视频帧的大小方面遇到问题,则可以使用以下内容替换drawImage()参数:

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);

这篇关于如何使用javascript获取html5视频的缩略图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆