Skip to content
Related Articles

Related Articles

How to open web cam in JavaScript ?

View Discussion
Improve Article
Save Article
  • Last Updated : 31 Mar, 2021
View Discussion
Improve Article
Save Article

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.

Syntax :

var mediaDevices = navigator.mediaDevices;



<!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>Web Cam</title>
      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.
              video: true,
              audio: true,
            .then((stream) => {
              // Changing the source of video to current stream.
              video.srcObject = stream;
              video.addEventListener("loadedmetadata", () => {
    div {
      width: 500px;
      height: 400px;
      border: 2px solid black;
      position: relative;
    video {
      width: 500px;
      height: 400px;
      object-fit: cover;
        <video id="vid"></video>
      <br />
      <button id="but" autoplay>
        Open WebCam

Output :

  • Before clicking the button : 

  • After clicking the button : 

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!