Javascript如何从视频中提取帧?

时间:2017-03-24 19:26:51

标签: javascript html css video

您好,我有以下JS代码,可以从文件输入中创建视频:

<canvas  id="prevImgCanvas">Your browser does not support the HTML5 canvas tag.</canvas> 

<input id="videoage" type="file" name="video" class="chooseNail" accept="video/*" style="display:none;" onchange="loadSnippetThumb(event)">
<label for="videoage" id="labelvideo" >Choose Video</label>

var loadSnippetThumb = function(event) {                
    var c = document.getElementById("prevImgCanvas");
    var context = c.getContext('2d');
    var url = URL.createObjectURL(event.target.files[0]);
    var video = document.getElementById('video222');
    video.src = url;
    video.autoPlay = true;

}

这将创建一个在用户选择使用文件输入上传的屏幕上播放的视频。我不希望视频显示在屏幕上我只是希望能够选择视频的随机帧并将其显示在画布上。我怎样才能做到这一点? 感谢。

1 个答案:

答案 0 :(得分:0)

seekedloadeddata个事件上添加一个监听器,并在currentTime事件中设置loadeddata,以获得正确的video.duration。此时将调用seeked事件并绘制您的视频帧:

&#13;
&#13;
var video = document.createElement("video");

var canvas = document.getElementById("prevImgCanvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

video.addEventListener('loadeddata', function() {
  reloadRandomFrame();
}, false);

video.addEventListener('seeked', function() {
  var context = canvas.getContext('2d');
  context.drawImage(video, 0, 0, canvas.width, canvas.height);
}, false);

var playSelectedFile = function(event) {
  var file = this.files[0];
  var fileURL = URL.createObjectURL(file);
  video.src = fileURL;
}

var input = document.querySelector('input');
input.addEventListener('change', playSelectedFile, false);

function reloadRandomFrame() {
  if (!isNaN(video.duration)) {
    var rand = Math.round(Math.random() * video.duration * 1000) + 1;
    video.currentTime = rand / 1000;
  }
}
&#13;
<input type="file" accept="video/*" />
<input type="submit" onClick="reloadRandomFrame()" value="load random frame" /><br/>
<canvas id="prevImgCanvas">Your browser does not support the HTML5 canvas tag.</canvas>
&#13;
&#13;
&#13;

JSFiddle here

中的相同代码