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">
    <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>

Now, we need to implement a <video> tag for streaming the webcam.

  <video width="500px" height="500px" id="webcam" autoplay></video>

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) {


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.

Written by Aravind Sanjeev, an India-based blogger and web developer. Read all his posts. You can also find him on twitter.