Skip to content

Instantly share code, notes, and snippets.

@webapprentice
Last active January 1, 2016 20:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save webapprentice/8199291 to your computer and use it in GitHub Desktop.
Save webapprentice/8199291 to your computer and use it in GitHub Desktop.
<video id="video"></video>
<br>
<div id="controls">
<button id="start_button">Start Video</button> &nbsp;
<button id="stop_button">Stop Video</button> &nbsp;
<button id="capture_button">Capture Photo</button>
</div>
<br>
<canvas id="canvas"></canvas>
<!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -->
<style>
button {
font-size: 16pt;
}
#controls {
margin-left: auto;
margin-right: auto;
display: block;
text-align: center;
}
#canvas {
margin-left: auto;
margin-right: auto;
display: block;
background-color: #eee;
border: 1px solid black;
}
#video {
margin-left: auto;
margin-right: auto;
display: block;
border: 1px solid black;
}
</style>
<!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -->
<script>
// Hack to handle vendor prefixes
navigator.getUserMedia = ( navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia);
var video = document.querySelector('video');
var canvas = document.querySelector('canvas');
var ctx;
var width = 480;
var height = 0;
var mediaStream;
var streaming;
$(document).ready(function() {
if(!navigator.getUserMedia) {
alert("Sorry - your browser does not support getUserMedia - try Chrome or Firefox");
}
ctx = canvas.getContext("2d");
// Set up video Start button
$("body").on('click', "#start_button",function(e) {
e.preventDefault();
navigator.getUserMedia(
{
video: true,
audio: false
},
function(stream) {
if (navigator.mozGetUserMedia) {
video.mozSrcObject = stream;
} else {
var url = window.URL || window.webkitURL;
video.src = url ? url.createObjectURL(stream) : stream;
}
mediaStream = stream;
video.play();
},
function(error) {
console.log("ERROR: " + error);
}
);
});
// Set up video Stop button
$("body").on('click', "#stop_button", function(e) {
e.preventDefault();
mediaStream.stop();
});
// Set up the Image Capture button
$("body").on('click', "#capture_button", function(e) {
e.preventDefault();
// ?? In Firefox I need to set this here to resize the canvas
height = video.videoHeight / (video.videoWidth / width);
canvas.setAttribute('width', width);
canvas.setAttribute('height', height);
ctx.drawImage(video, 0, 0, width, height);
});
// Get the dimensions and scale the video when stream is ready to play,
$("video").on('canplay', function(e) {
if (!streaming) {
height = video.videoHeight / (video.videoWidth / width);
video.setAttribute('width', width);
video.setAttribute('height', height);
streaming = true;
}
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment