Take a Screenshot of video

Take a Screenshot of video

by onigetoc

HTML

<link rel="stylesheet" href="//vjs.zencdn.net/5.4.6/video-js.min.css">
<script src="//vjs.zencdn.net/5.4.6/video.min.js"></script>
<video id="myvideo" class="video-js vjs-fluid vjs-tech" controls="controls" width="400" height="150" data-setup="{}" poster="http://www.allotoi.com/wp-content/uploads/2014/07/rickyPepe.jpg">
<source src="http://podcast.rickygervais.com/rickyandpepe_twitter.mp4" type="video/mp4" />
</video>
<!-- <video preload="none" controls>
  <source src="http://podcast.rickygervais.com/rickyandpepe_twitter.mp4" type="video/mp4" />
</video> -->
<button id="snap" onclick="snap()">Snap Photo</button>
<canvas id="canvas" width="640" height="480"></canvas>

JavaScript

var video = document.querySelector('video');
     var canvas = document.querySelector('canvas');
     var context = canvas.getContext('2d');
     var w, h, ratio;
     //add loadedmetadata which will helps to identify video attributes......
     video.addEventListener('loadedmetadata', function() {
       ratio = video.videoWidth / video.videoHeight;
       w = video.videoWidth - 100;
       h = parseInt(w / ratio, 10);
       canvas.width = w;
       canvas.height = h;
     }, false);
     ///define a function
     function snap() {
       context.fillRect(0, 0, w, h);
       context.drawImage(video, 0, 0, w, h);
     }