2017-03-24 176 views
-1

你好,我有一個創建從一個文件輸入的視頻下面的JS代碼:Javascript如何從視頻中提取幀?

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

} 

這將創建一個在屏幕上,用戶已經選擇使用文件輸入上傳播放視頻。我不希望視頻在屏幕上顯示,我只是希望能夠挑選視頻的隨機幀並將其顯示在畫布上。我怎樣才能做到這一點? 謝謝。

回答

0

loadeddata事件添加監聽器seekedloadeddata事件,並設置currentTime,以獲得正確的video.duration。該seeked事件將被調用,並在這個時刻提醒你的視頻幀:在的jsfiddle here

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

相同的代碼