Skip to content

Instantly share code, notes, and snippets.

@romgrk
Last active September 26, 2016 20:31
Show Gist options
  • Select an option

  • Save romgrk/11bf279c35dcea617e072f70239a3ccb to your computer and use it in GitHub Desktop.

Select an option

Save romgrk/11bf279c35dcea617e072f70239a3ccb to your computer and use it in GitHub Desktop.
take a picture in the browser using the webcam
// Pops up a popup to take a picture in the browser using the webcam. (Vanilla JS)
// Returns a promise which resolves to a data URI ('image/jpeg;base64,...')
// Tested with chrome 54.x
//
// Example:
// capturePhoto().then(data => document.querySelector('img').src = data)
//
// MIT license. Romgrk, 2016.
const capturePhoto = () => {
return new Promise((resolve, reject) => {
var container = document.createElement('div');
var video = document.createElement('video');
var canvas = document.createElement('canvas');
container.appendChild(video);
container.appendChild(canvas);
container.style.position = 'fixed';
container.style.zIndex = '100';
container.style.top = '0';
container.style.left = '0';
container.style.width = '100%';
container.style.height = '100%';
container.style.padding = '100px';
container.style.backgroundColor = 'rgba(0,0,0,0.3)';
video.style.width = '100%';
video.style.height = '100%';
canvas.style.opacity = '0';
const init = stream => {
video.src = URL.createObjectURL(stream);
video.addEventListener('click', ev => {
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
canvas.getContext('2d').drawImage(video, 0, 0)
var data = canvas.toDataURL('image/jpeg');
stream.getTracks()[0].stop();
document.body.removeChild(container);
resolve(data);
})
}
navigator.mediaDevices
.getUserMedia({video: true})
.then(init)
.catch(err => reject(err));
document.body.appendChild(container);
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment