Skip to content

Instantly share code, notes, and snippets.

@CristhianMotoche
Last active April 25, 2017 20:16
Show Gist options
  • Save CristhianMotoche/a73c402957121a3a7237833c6e193ef6 to your computer and use it in GitHub Desktop.
Save CristhianMotoche/a73c402957121a3a7237833c6e193ef6 to your computer and use it in GitHub Desktop.
Using the camera with HTML5
<!DOCTYPE html>
<html lang="en" dir="ltr" xmlns:fb="http://ogp.me/ns/fb#">
<head>
<meta charset="utf-8" />
<title>Camera and Video Control with HTML5 Example</title>
<style>
video { border: 1px solid #ccc; display: block; margin: 0 0 20px 0; }
#canvas { margin-top: 20px; border: 1px solid #ccc; display: block; }
</style>
</head>
<body>
<video id="video" width="640" height="480" autoplay></video>
<button id="snap" class="sexyButton">Snap Photo</button>
<canvas id="canvas" width="640" height="480"></canvas>
<script>
// Put event listeners into place
window.addEventListener("DOMContentLoaded", function() {
// Grab elements, create settings, etc.
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var video = document.getElementById('video');
var mediaConfig = { video: true };
var errBack = function(e) {
console.log('An error has occurred!', e)
};
// Put video listeners into place
if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia(mediaConfig).then(function(stream) {
video.src = window.URL.createObjectURL(stream);
video.play();
});
}
/* Legacy code below! */
else if(navigator.getUserMedia) { // Standard
navigator.getUserMedia(mediaConfig, function(stream) {
video.src = stream;
video.play();
}, errBack);
} else if(navigator.webkitGetUserMedia) { // WebKit-prefixed
navigator.webkitGetUserMedia(mediaConfig, function(stream){
video.src = window.webkitURL.createObjectURL(stream);
video.play();
}, errBack);
} else if(navigator.mozGetUserMedia) { // Mozilla-prefixed
navigator.mozGetUserMedia(mediaConfig, function(stream){
video.src = window.URL.createObjectURL(stream);
video.play();
}, errBack);
}
// Trigger photo take
document.getElementById('snap').addEventListener('click', function() {
context.drawImage(video, 0, 0, 640, 480);
});
}, false);
</script>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment