Last active
January 29, 2017 19:38
-
-
Save TobiasSeitz/b75676055dbd19d1618d63d3e36cb488 to your computer and use it in GitHub Desktop.
How to use MediaDevices API to take picture from a web cam with getUserMedia
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>HTML5 Media Device Access</title> | |
<meta name="viewport" content="width=device-width, initial-scale=1"> | |
<style> | |
video, img { | |
max-width:100%; | |
} | |
</style> | |
</head> | |
<body> | |
<video autoplay></video> | |
<script> | |
(function() { | |
'use strict'; | |
var video = document.querySelector('video') | |
, canvas; | |
/** | |
* generates a still frame image from the stream in the <video> | |
* appends the image to the <body> | |
*/ | |
function takeSnapshot() { | |
var img = document.querySelector('img') || document.createElement('img'); | |
var context; | |
var width = video.offsetWidth | |
, height = video.offsetHeight; | |
canvas = canvas || document.createElement('canvas'); | |
canvas.width = width; | |
canvas.height = height; | |
context = canvas.getContext('2d'); | |
context.drawImage(video, 0, 0, width, height); | |
img.src = canvas.toDataURL('image/png'); | |
document.body.appendChild(img); | |
} | |
// use MediaDevices API | |
// docs: https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia | |
if (navigator.mediaDevices) { | |
// access the web cam | |
navigator.mediaDevices.getUserMedia({video: true}) | |
// permission granted: | |
.then(function(stream) { | |
video.src = window.URL.createObjectURL(stream); | |
video.addEventListener('click', takeSnapshot); | |
}) | |
// permission denied: | |
.catch(function(error) { | |
document.body.textContent = 'Could not access the camera. Error: ' + error.name; | |
}); | |
} | |
})(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment