Skip to content

Instantly share code, notes, and snippets.

@chulman444
Created September 21, 2018 04:53
Show Gist options
  • Save chulman444/32fb6b02d9503c63a6f6bac3617224ae to your computer and use it in GitHub Desktop.
Save chulman444/32fb6b02d9503c63a6f6bac3617224ae to your computer and use it in GitHub Desktop.
See your webcam on the browser and take a screenshot of the webcam
<video autoplay="true" id="videoElement">
</video>
<button onclick="captureVideo()">capture</button>
<canvas id="myCanvas"/>
<script>
function main() {
var video = document.querySelector("#videoElement");
if (navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia({video: true})
.then(function(stream) {
video.srcObject = stream;
})
.catch(function(err0r) {
console.log("Something went wrong!");
});
}
/**
* The browser asks whether to allow the webcam or not.
*/
videoElement.addEventListener("playing", ()=> {
/**
* Video element attributes are not available, or does not
* have the desired value until it is "playing".
*
* So set the canvas size when it has the desired value.
*/
myCanvas.width = videoElement.videoWidth;
myCanvas.height = videoElement.videoHeight;
});
}
function captureVideo() {
console.log("capture video");
myCanvas.getContext('2d').drawImage(videoElement, 0,0);
}
main()
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment