Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to open web cam in JavaScript ?

  • Last Updated : 31 Mar, 2021

In this article, we will see how to open a webcam and show a live video using JavaScript. For this we are going to use Navigator media Devices.

Navigator Media Devices: It is a read-only property that returns a Media Devices object, which helps us to access the connected media input devices like camera and microphone.

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

Syntax :

var mediaDevices = navigator.mediaDevices;

Example:



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>Web Cam</title>
    <script>
      document.addEventListener("DOMContentLoaded", () => {
        var but = document.getElementById("but");
        var video = document.getElementById("vid");
        var mediaDevices = navigator.mediaDevices;
        vid.muted = true;
        but.addEventListener("click", () => {
  
          // Accessing the user camera and video.
          mediaDevices
            .getUserMedia({
              video: true,
              audio: true,
            })
            .then((stream) => {
  
              // Changing the source of video to current stream.
              video.srcObject = stream;
              video.addEventListener("loadedmetadata", () => {
                video.play();
              });
            })
            .catch(alert);
        });
      });
    </script>
  </head>
  
  <style>
    div {
      width: 500px;
      height: 400px;
      border: 2px solid black;
      position: relative;
    }
    video {
      width: 500px;
      height: 400px;
      object-fit: cover;
    }
  </style>
  
  <body>
    <center>
      <div>
        <video id="vid"></video>
      </div>
      <br />
      <button id="but" autoplay>
        Open WebCam
      </button>
    </center>
  </body>
</html>

Output :

  • Before clicking the button : 

  • After clicking the button : 




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!