Skip to content

Instantly share code, notes, and snippets.

@bengillies
Created December 8, 2014 13:23
Show Gist options
  • Save bengillies/7679f4627b77445a1cd2 to your computer and use it in GitHub Desktop.
Save bengillies/7679f4627b77445a1cd2 to your computer and use it in GitHub Desktop.
Take picture
<!DOCTYPE html>
<html>
<head>
<title>Take Picture</title>
</head>
<body>
<video autoplay></video>
<canvas></canvas>
<button>Click</button>
<select></select>
<script>
navigator.getUserMedia = (navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia);
window.URL = window.URL || window.webkitURL;
var video = document.querySelector('video');
var canvas = document.querySelector('canvas');
var button = document.querySelector('button');
var select = document.querySelector('select');
var videoSources = [];
var context = { video: true };
canvas.style.display = 'none';
button.style.display = 'none';
select.style.display = 'none';
if (navigator.getUserMedia) {
if (window['MediaStreamTrack'] && window.MediaStreamTrack['getSources']) {
MediaStreamTrack.getSources(function(sources) {
for (var i = 0, l = sources.length; i < l; i++) {
if (sources[i].kind == 'video') {
videoSources.push({
id: sources[i].id,
description: 'Camera ' + (videoSources.length + 1)
});
}
}
if (videoSources.length) {
videoSources.forEach(function(source) {
var option = document.createElement('option');
option.textContent = source.description;
option.value = source.id;
select.appendChild(option);
});
select.style.display = 'block';
select.addEventListener('change', function(ev) {
context.video = {
optional: [{ sourceId: select.value }]
};
updateVideo();
});
}
});
}
var updateVideo = (function () {
var stream;
return function() {
if (stream) {
stream.stop();
stream = null;
}
navigator.getUserMedia(context, function(_stream) {
stream = _stream;
video.src = window.URL.createObjectURL(stream);
button.style.display = 'block';
}, function(err) {
console.log('There was an error:', err);
});
};
}());
document.querySelector('button').addEventListener('click', function(ev) {
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
video.style.display = 'none';
canvas.getContext('2d').drawImage(video, 0, 0);
canvas.style.display = 'block';
var img = canvas.toDataURL('image/jpeg');
var base64 = img.slice(img.indexOf(',') + 1);
console.log(img.slice(0, 30));
console.log(base64.slice(0, 30));
});
updateVideo();
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment