Skip to content

Instantly share code, notes, and snippets.

@a7maadf
Created May 21, 2023 05:35
Show Gist options
  • Save a7maadf/ae8bc1d15b862edfd1d7839cbc4f4201 to your computer and use it in GitHub Desktop.
Save a7maadf/ae8bc1d15b862edfd1d7839cbc4f4201 to your computer and use it in GitHub Desktop.
Simple Webcam input in HTML
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>
<button onclick="startWebcam();">Start WebCam</button>
<button onclick="getCurrentFrame();">Take Snapshot</button>
</p>
<!-- <video id="video" hidden autoplay></video> -->
<!-- <canvas id="myCanvas" hidden></canvas> -->
<img id="my-data-uri" src="">
</body>
<script src="webcam.js"></script>
</html>
var canvas
var ctx
var video;
var webcamWidth;
var webcamHeight;
navigator.getUserMedia = (
navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia
);
function startWebcam() {
// canvas = document.getElementById("myCanvas")
// video = document.getElementById('video')
canvas = document.createElement('canvas')
video = document.createElement('video')
video.setAttribute('autoplay', true)
ctx = canvas.getContext('2d')
if (navigator.getUserMedia) {
navigator.getUserMedia (
{
video: true,
audio: false
},
function(stream) {
webcamWidth = stream.getVideoTracks()[0].getSettings().width
webcamHeight = stream.getVideoTracks()[0].getSettings().height
canvas.setAttribute('width', webcamWidth);
canvas.setAttribute('height', webcamHeight);
// video.src = window.URL.createObjectURL(localMediaStream);
video.srcObject = stream
},
function(err) {
console.log( err);
}
);
} else {
console.log("getUserMedia not supported by your browser");
}
}
function getCurrentFrame() {
ctx.drawImage(video, 0,0)
img_dataURI = canvas.toDataURL('image/png')
document.getElementById("my-data-uri").src = img_dataURI
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment