Webcam to Video to Canvas
by laustdeleuran
HTML
<h1>Video</h1>
<video id="stream"></video>
<h1>Canvas</h1>
<canvas id="surface"></canvas>
<h1>Image</h1>
<button id="snap">Take snapshot</button>
<img id="picture" />
CSS
body {
background:#eee;
font-family:sans-serif;
text-align:center;
}
h1 {
font-size:1em;
display:block;
}
#stream, #surface, #picture {
display:block;
margin:15px auto;
background:#333;
border:5px solid #ddd;
}
JavaScript
// Animation frame shim
// shim layer with setTimeout fallback - https://gist.github.com/paulirish/1579671
(function() {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame']
|| window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}());
// getUserMedia shim
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
// Actual good stuff
if (navigator.getUserMedia) {
(function () {
var video, canvas, image, button, context, frame, draw, dimensions;
video = document.getElementById('stream');
canvas = document.getElementById('surface');
image = document.getElementById('picture');
button = document.getElementById('snap');
context = canvas.getContext('2d');
draw = function () {
if (!dimensions || dimensions.width !== video.videoWidth || dimensions.height !== video.videoHeight) {
dimensions = {
width: video.videoWidth,
height:...