Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript how to extract frame from video?

Hello I have the following JS code that creates a video from a file input:

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

}

This creates a video that plays on screen that the user has chosen to upload using the file input. I don't want the video to display on screen I just want to be able to pick out a random frame of the video and displays it on the canvas. How can I do this? Thanks.

like image 418
bobby Avatar asked Mar 24 '17 19:03

bobby


1 Answers

Add a listener on seeked and loadeddata events and set currentTime in the loadeddata event in order to get the correct video.duration. The seeked event will get called and draw your video frame at this moment :

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>

The same code in a JSFiddle here

like image 87
Bertrand Martel Avatar answered Sep 20 '22 13:09

Bertrand Martel