Delayed webcam to canvas

by alessandro_pezzato

HTML

<script src="https://raw.github.com/mrdoob/three.js/master/src/Three.js"></script>
    <div id="container"></div>
    <video id="video"></video>

JavaScript

var video = null;
var time = null;
var frames = [];
var framesNum = 32;
var videoWidth = 128;
var videoHeight = 96;
var skip = 5;
var skipCounter = 0;

$(function() {
    init();
    animate();
});

function init() { /* texture from webcam */
    video = $('#video').get(0);
    video.width = videoWidth;
    video.height = videoHeight;
    video.autoplay = true;
    video.style.opacity = 1;
    video.available = false;

    /* frames */
    for (var i = 0; i != framesNum; ++i) {
        var frameCanvas = $('<canvas/>');
        frameCanvas.attr('id', 'frame' + i);
        frameCanvas.attr('width', videoWidth);
        frameCanvas.attr('height', videoHeight);
        $('#container').append(frameCanvas);
        var frameContext = frameCanvas[0].getContext('2d');
        frames[i] = frameContext;
    }

    /* initialize webcam */
    initWebcam();
}

/**
 * called by requestAnimationFrame
 */
function animate() {
    requestAnimationFrame(animate);
    var now = new Date().getTime();
    var dt = now - (time || now);
    time = now;
    onFrame(dt / 1000);
}

/**
 * updates sprites' map textures 1 become 0, 2 become 1... (called every second)
 */
function rotateFrames() {
    for (var i = 0; i != framesNum - 1; ++i) {
        var data = frames[i + 1].getImageData(0, 0, videoWidth, videoHeight);
        frames[i].putImageData(data, 0, 0);
    }
}

/**
 * called on each rendering frame
 * 
 * @param dt
 *            delta-time (time since lasta frame)
 */
function onFrame(dt) {
    if (video.available) {
        if (video.readyState === video.HAVE_ENOUGH_DATA) {
            frames[framesNum - 1].drawImage(video, 0, 0, video.width, video.height);
            if (++skipCounter == skip) {
                rotateFrames();
                skipCounter = 0;
            }
        }
    }
}

/**
 * initialize webcam stream
 */
function initWebcam() {
    navigator.webkitGetUserMedia({
        audio: false,
        video: true
    }, function(stream) {
        video.src =...