HTML5显示视频的缩略图预览

时间:2015-10-22 15:59:46

标签: javascript jquery html 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);
 }

1 个答案:

答案 0 :(得分:2)

解决了!

我需要添加一个在视频数据加载后绘制画布的事件

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