M9A
M9A

Reputation: 3276

HTML5 Display Thumbnail preview of Video

I have an input file field that allows a user to upload a video file. On selecting the file, I want the thumbnail of the video to appear as a preview before the user decides to upload the file. For some reason, the image preview does not show.

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

Upvotes: 2

Views: 5301

Answers (1)

M9A
M9A

Reputation: 3276

Solved it!

I needed to add an event that draws the canvas once the video data has loaded

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

Upvotes: 3

Related Questions