Streaming your webcam to an HTML document is a short & simple process. We start by creating a plain HTML document (call it index.html).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Your Face</title>
</head>
<body>
</body>
</html>
Now, we need to implement a <video>
tag for streaming the webcam.
<body>
<video width="500px" height="500px" id="webcam" autoplay></video>
</body>
In a separate JavaScript file (index.js), we write code to access the webcam.
const video = document.getElementById("webcam")
async function getMedia() {
let stream = null
try {
stream = await navigator.mediaDevices.getUserMedia({ video: true })
video.srcObject = stream
} catch (err) {
console.log("error")
}
}
getMedia()
In the code, we grabbed the element by ID and stored it in variable video
. It is important that we are using asynchronous function so the browser doesn't freeze on delay. The navigator.mediaDevices
contains methods that is used to interact with input devices. The stream is stored and passed as source object to the video
.
Finally, we need to import this back to the HTML document. In the <head>
section,
<script defer src="index.js"></script>
The defer
attribute will ensure that the JavaScript is executed only after the page is loaded.
Now open your HTML document and it will ask for permission to access the camera. Click allow and smile.