taking screenshots from user's webcam
by trixta
HTML
<script src="http://afarkas.github.io/webshim/js-webshim/minified/polyfiller.js"></script>
<div class="player">
<div class="screenshot-wrapper">
<div class="mediaplayer">
<video controls preload="none" autoplay=""></video>
</div>
<button type="button" disabled="" class="screenshot-btn">take a photo</button>
<div class="canvas-holder">
<canvas></canvas>
</div>
</div>
<hr />
<p><a href="http://afarkas.github.io/webshim/demos/index.html#Media-elements">webshims mediaelement documentation</a>
</p>
CSS
.player {
margin: auto;
padding: 10px;
width: 90%;
max-width: 900px;
min-width: 320px;
}
.mediaplayer, .canvas-holder {
position: relative;
height: 0;
width: 100%;
padding-bottom: 75%;
}
.mediaplayer video, .mediaplayer .polyfill-video, .canvas-holder canvas {
position: absolute;
top: 0;
left: 0;
height: 100%;
width: 100%;
}
JavaScript
webshim.setOptions('mediaelement', {
replaceUI: 'auto'
});
webshim.setOptions({
canvas: {
type: 'flash' //for IE8 support
},
mediaelement: {
replaceUI: 'auto'
}
});
webshim.polyfill('mediaelement canvas usermedia');
$(function () {
$('.screenshot-wrapper').each(function () {
var $module = $(this);
var context = $('canvas', $module).getContext('2d');
var $video = $('video', $module);
function takeScreenshot() {
context.drawImage($video[0], 0, 0);
}
$('.screenshot-btn', $module).on('click', takeScreenshot);
$video.on('loadedmetadata', function () {
setTimeout(function () {
$('canvas', $module).attr({
width: $.prop(this, 'videoWidth') || 640,
height: $.prop(this, 'videoHeight') || 480
});
$('.screenshot-btn', $module).prop('disabled', false);
});
});
});
});
$(function () {
navigator.getUserMedia(
// constraints
{
video: true,
audio: false
},
// successCallback
function (localMediaStream) {
var $video = $('video');
$video.on('loadstart', function () {
$video.play();
});
$video.prop('src', URL.createObjectURL(localMediaStream));
//or use $video.prop('srcObject', localMediaStream);
},
// errorCallback
function (err) {
alert('you need to give us access to your webcam for this. '+err.name);
});
});