Skip to content

Instantly share code, notes, and snippets.

@tbhaxor
Created April 10, 2020 13:32
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 tbhaxor/ea8d9e61495e7649958d4e75911b4a83 to your computer and use it in GitHub Desktop.
Save tbhaxor/ea8d9e61495e7649958d4e75911b4a83 to your computer and use it in GitHub Desktop.
Capture profile pic from webcam using WebRTC Media API
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Capture Profile Pic</title>
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
<style>
video {
max-width: 240px;
min-width: 240px;
max-height: 240px;
min-height: 240px;
}
</style>
</head>
<body>
<video autoplay></video>
<button id="capture">Capture Profile Pic</button>
<p>Working</p>
<p>Profile pic will display here</p>
<canvas style="display: none;"></canvas>
<div>
<img />
</div>
<script>
var img = document.querySelector("img");
var canvas = document.querySelector("canvas");
var video = document.querySelector("video");
var button = document.querySelector("button");
var streaming = false;
var width = 240;
var height = 240;
video.addEventListener("canplay", (ev) => {
if (!streaming) {
height = video.videoHeight / (video.videoWidth / width);
if (isNaN(height)) {
height = width / (4 / 3);
}
video.width = height;
video.height = width;
canvas.width = width;
canvas.height = height;
streaming = true;
}
});
function takeProfilePic() {
var ctx = canvas.getContext("2d");
if (width && height) {
canvas.width = width;
canvas.height = height;
ctx.drawImage(video, 0, 0, width, height);
var data = canvas.toDataURL("image/png");
img.src = data;
}
}
button.addEventListener("click", (e) => {
e.preventDefault();
takeProfilePic();
});
console.log(navigator);
navigator.mediaDevices
.getUserMedia({
audio: false,
video: true,
})
.then((stream) => {
document.querySelector("p").textContent = "Connected";
video = document.querySelector("video");
video.srcObject = stream;
video.play();
})
.catch((e) => {
alert(e);
document.querySelector("p").textContent = "Not Connected";
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment