javascript从视频网址生成视频缩略图

时间:2016-10-20 01:16:48

标签: javascript jquery dom canvas html5-video

我将在javascript中从视频网址生成视频缩略图。 我需要通过ajax完成此操作。 所以我采用了这种方法。

var src = thumbnail; ///video url not youtube or vimeo,just video on server
var video = document.createElement('video');

video.src = src;

video.width = 360;
video.height = 240;

var canvas = document.createElement('canvas');
canvas.width = 360; 
canvas.height = 240;
var context = canvas.getContext('2d');

context.drawImage(video, 0, 0, canvas.width, canvas.height);
var dataURI = canvas.toDataURL('image/jpeg');
html += '<figure>';
html += '<img src="' + dataURI + '' + '" alt="' + item.description + '" />';
html += '<figurecaption>'+item.description+'</figurecaption>'
html += '</figure>';

但我得到的只是黑色图像。 我想这是因为加载问题但无法找到解决方案。 期待收到你的回复。

问候。

3 个答案:

答案 0 :(得分:2)

您可以安装npm:video-metadata-thumbnails,然后像这样使用它:

import { getMetadata, getThumbnails } from 'video-metadata-thumbnails';

const thumbnails = await getThumbnails(blob, {
  quality: 0.6
});
console.log('Thumbnails: ', thumbnails);

答案 1 :(得分:0)

  

但是我得到的只是黑色图像。我想这是因为负载问题,但是找不到解决方案。期待您的回音。

那可能是因为在您呼叫的那一刻还没有加载任何帧:

context.drawImage(video, 0, 0, canvas.width, canvas.height);

您应该在收到一些“ loadeddata”事件后执行此操作(检查https://developer.mozilla.org/en-US/docs/Web/Events/loadeddata

因此您的代码将变为:

var src = thumbnail; ///video url not youtube or vimeo,just video on server
var video = document.createElement('video');

video.src = src;

video.width = 360;
video.height = 240;

var canvas = document.createElement('canvas');
canvas.width = 360; 
canvas.height = 240;
var context = canvas.getContext('2d');

video.addEventListener('loadeddata', function() {
    context.drawImage(video, 0, 0, canvas.width, canvas.height);
    var dataURI = canvas.toDataURL('image/jpeg');
    html += '<figure>';
    html += '<img src="' + dataURI + '' + '" alt="' + item.description + '" />';
    html += '<figurecaption>'+item.description+'</figurecaption>'
    html += '</figure>';
});

请注意,这将是异步的,因此也许您必须更改对该html变量的处理方式,然后设置image.src = dataURI;,即image是对Image DOM节点的引用(您插入的那个)

答案 2 :(得分:0)

我遇到了同样的问题,我通过使用“ loadeddata”事件解决了这个问题,但是我还必须添加cors属性并播放/暂停视频:

var video = document.createElement('video');

var canvas = document.createElement('canvas');
var context = canvas.getContext('2d')
video.addEventListener('loadeddata', function() {
  context.drawImage(video, 0, 0, canvas.width, canvas.height);
  video.pause();

  var dataURI = canvas.toDataURL('image/jpeg');
  var img = document.createElement("img");
  img.src = dataURI;
  that.css('background-image', 'url(' + dataURI + ')');
}, false);

video.preload = 'metadata';
video.muted = true;
video.playsInline = true;
video.setAttribute('crossOrigin', 'anonymous');
video.src = $(this).data('src');
video.play();