2015-10-22 102 views
2

我有一個輸入文件字段,允許用戶上傳視頻文件。在選擇文件時,我希望視頻的縮略圖在用戶決定上傳文件之前顯示爲預覽。出於某種原因,圖像預覽不顯示。HTML5顯示視頻的縮略圖預覽

<input type="file" name="browseVideos" id="browseVideos" multiple="multiple" accept="video/*"> 
<output id="listVideos"></output> 

document.getElementById('browseVideos').addEventListener('change', handleVideoSelect, true); 

function handleVideoSelect(evt) { 
    var files = evt.target.files; // FileList object 

    // Loop through the FileList and render video files as thumbnails. 
    for (var i = 0; i < files.length; i++) { 
     var f = files[i]; 
     // Only process video files. 
     if (!f.type.match('video.*')) { 
      continue; 
     } 
     createVideoCanvas(f); 
    } 
} 

function createVideoCanvas(f){ 
    var vid = document.createElement('video'); 
    vid.src = window.URL.createObjectURL(f); 
    var canvas = document.createElement('canvas'); 
    canvas.width = 105; 
    canvas.height = 100; 
    canvas.getContext("2d").drawImage(vid, 0, 0, 100, 100); 
    window.URL.revokeObjectURL(f);     
    document.getElementById('listVideos').appendChild(canvas); 
} 

回答

2

解決了!

我需要添加一次視頻數據加載

vid.addEventListener('loadeddata', function() { 
     canvas.getContext("2d").drawImage(vid, 0, 0, 100, 100); 
}, false); 
+0

喜繪製在畫布上,我一直在努力解決方案,我們需要添加事件的事件? – apr

+1

Matt9Atkins在這個答案中給出的代碼替換了他的問題中的'canvas.getContext(「2d」)「......行。我已經證實這是有效的(只要瀏覽器支持播放被選擇的視頻類型,顯然)。 – tremby