Skip to content

Instantly share code, notes, and snippets.

@wallacemaxters
Last active November 30, 2015 11:42
Show Gist options
  • Save wallacemaxters/1fa6d250e574eab6eae4 to your computer and use it in GitHub Desktop.
Save wallacemaxters/1fa6d250e574eab6eae4 to your computer and use it in GitHub Desktop.
(function ( $ ) {
function userMedia()
{
var n = navigator,
args = arguments;
return (n.getUserMedia ||
n.webkitGetUserMedia ||
n.mozGetUserMedia ||
n.msGetUserMedia).apply(n, args);
}
var url = window.URL || window.webkitURL;
var _stream = null;
function stopWebcam()
{
return _stream && _stream.stop();
}
var optionsCommands = {
stop: 'stop',
}
$.fn.wmcam = function (options) {
var $el = this;
if (options == optionsCommands.stop) {
var stop = $el.data('stopWmcam');
$.isFunction(stop) && stop();
return this;
}
options = $.extend({
width: 350,
triggerSnap: '.wm-cam-take',
triggerCancel: '.wm-cam-reopen'
}, options);
$el.data({
stopWmcam: stopWebcam,
});
if (options.video) {
var $video = $(options.video);
if ($video.size() == 0) {
throw new Error('Element "video" not exists in DOM');
}
} else {
var $video = $('<video />').appendTo($el);
}
$video.attr({
width: options.width,
autoplay: true,
control: false,
});
var video = $video.get(0);
if (options.image) {
var $image = $(options.image);
if ($image.size() == 0) {
throw new Error('Element "image" not exists in DOM');
}
} else {
var $image = $('<img />', {
width: options.width,
}).hide();
$image.append($image);
}
function onStream (stream)
{
_stream = stream;
var blob = url.createObjectURL(stream);
$video.attr({src: blob});
var $button = $(options.triggerCancel);
return $.isFunction(options.onCamera)
&& options.onCamera.call($button, $video, _stream)
}
function onError ()
{
return $.isFunction(options.onError) && options.onError.call($el);
}
try {
userMedia({video:true}, onStream, onError);
} catch (e) {
onError();
}
$(document).on('click', options.triggerSnap, function (e) {
e.preventDefault();
var height = $video.height(),
width = $video.width();
var $canvas = $('<canvas />').attr({
width: width,
height: height,
});
var canvas = $canvas.get(0);
canvas.getContext('2d').drawImage(video, 0, 0, width, height);
var src = canvas.toDataURL();
var base64 = src.split(',')[1];
$image.attr({src: src}).bind('load.wm-cam', function ()
{
$image.unbind('load.wm-cam');
$video.hide(0, function () {
$image.show();
});
});
options.onSnap.call(this, base64);
});
$(document).on('click', options.triggerCancel, function (e) {
e.preventDefault();
$image.hide(0, function () {
$video.show();
});
$.isFunction(options.onCamera) && options.onCamera.call(this, $video, _stream);
});
}
})( jQuery );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment