Extract frames from HTML5 video

by rusci

HTML

<!DOCTYPE html>
<title>Video/Canvas Demo 1</title>

<canvas id="c"></canvas>
<video id="v" controls loop>
<source type="video/webm; codecs=&quot;vp8, vorbis&quot;" src="http://www.html5rocks.com/tutorials/video/basics/Chrome_ImF.webm"></source>
    <source type="video/ogg; codecs=&quot;theora, vorbis&quot;" src="http://www.html5rocks.com/tutorials/video/basics/Chrome_ImF.ogv"></source>
    <source type="video/mp4; codecs=&quot;avc1.42E01E, mp4a.40.2&quot;" src="http://www.html5rocks.com/tutorials/video/basics/Chrome_ImF.mp4"></source>
</video>
<img src="" id="i"/>

CSS

body {
    background: black;
}

#c {
    width: 500px;
    height: 400px;
}

JavaScript

var v = document.getElementById('v');
var canvas = document.getElementById('c');
var context = canvas.getContext('2d');

var cw = canvas.width;
var ch = canvas.height

v.addEventListener('play', function(){
        draw(v,context,cw,ch);
    },false);

v.addEventListener('pause', function(){
        console.log('pause');
        var img = canvas.toDataURL('image/jpeg');
        $('#i').attr('width', cw).attr('height', ch).attr('src', img);
    },false);

function draw(v,c,w,h) {
    if(v.paused || v.ended) return false;
    c.drawImage(v,0,0,w,h);
    setTimeout(draw,20,v,c,w,h);
}