DailyDevDiet

logo - dailydevdiet

Learn. Build. Innovate. Elevate your coding skills with dailydevdiet!

How to Access WebCam Using JavaScript

access webcam using javascript

Introduction

The user’s device WebCam can be accessed using ECMAScript object navigator.mediaDevices.getUserMedia(). The getUserMedia() function returns a promise. Once you allow it, it enables the WebCam in your device. With JavaScript, not only can we view the WebCam feed, but we can also extend functionality to take snapshots and record video.

Follow these steps to access WebCam using JavaScript, snapshot capturing, and video recording in JavaScript.

Step 1: Set Up the HTML Structure

Create an HTML file and add elements like a video to show the WebCam stream and buttons for opening the WebCam, taking snapshots, and recording video.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="style.css" rel="stylesheet"/>
    <title>Access WebCam Using JavaScript</title>
</head>
<body>
    <div class="videoContainer">
        <video muted></video>
        <button id="openButton">Open WebCam</button>
        <button id="snapshotButton">Take Snapshot</button>
        <button id="recordButton">Start Recording</button>
        <canvas id="snapshotCanvas"></canvas>
        <a id="downloadLink" download="snapshot.png" style="display:none;">Download Snapshot</a>
        <a id="downloadVideo" download="recorded-video.webm" style="display:none;">Download Video</a>
    </div>
</body>
<script src="script.js"></script>
</html>

Here, the Open WebCam button starts the video stream. We’ve added two more buttons for the additional functionalities:

  • Take Snapshot – Captures an image from the video feed.
  • Start Recording – Starts and stops video recording.

The canvas element will be used to capture snapshots, and hidden anchor tags downloadLink and downloadVideo facilitate downloading snapshots and recorded videos.

Step 2: Apply Styling to Video Container and Buttons

Create a style.css file in the same folder and add the following styles to arrange the layout of the video container and buttons.

.videoContainer {
    width: 500px;
    height: 400px;
    border: 2px solid black;
    position: relative;
    margin: 0 auto;
    display: flex;
    flex-direction: column;
    align-items: center;
}

video {
    width: 500px;
    height: 400px;
    object-fit: cover;
    margin-bottom: 10px;
}

canvas {
    display: none;
}
button {
    margin: 5px;
}

The videoContainer styles center the content, while the video tag styles define the dimensions of the video feed display. The canvas is hidden since it’s only used for capturing snapshots.

Step 3: Write JavaScript to Access WebCam, Capture Snapshots, and Record Video

Add the following code to script.js to control the WebCam, capture snapshots, and handle video recording.

const video = document.querySelector("video");
const openButton = document.getElementById("openButton");
const snapshotButton = document.getElementById("snapshotButton");
const recordButton = document.getElementById("recordButton");
const canvas = document.getElementById("snapshotCanvas");
const downloadLink = document.getElementById("downloadLink");
const downloadVideo = document.getElementById("downloadVideo");

let mediaRecorder;
let recordedChunks = [];

// Step 3a: Access WebCam and Play Video Stream
openButton.addEventListener("click", function () {
  navigator.mediaDevices.getUserMedia({ video: true })
    .then((stream) => {
      video.srcObject = stream;
      video.play();
      snapshotButton.disabled = false;  // Enable snapshot button
      recordButton.disabled = false;    // Enable record button
    })
    .catch(error => console.error("Error accessing webcam:", error));
});

// Step 3b: Capture Snapshot
snapshotButton.addEventListener("click", function () {
  canvas.width = video.videoWidth;
  canvas.height = video.videoHeight;
  const context = canvas.getContext("2d");
  context.drawImage(video, 0, 0, canvas.width, canvas.height);
  
  const snapshotDataUrl = canvas.toDataURL("image/png");
  downloadLink.href = snapshotDataUrl;
  downloadLink.style.display = "block";
  downloadLink.click();
  downloadLink.style.display = "none";
});

// Step 3c: Record Video
recordButton.addEventListener("click", function () {
  if (mediaRecorder && mediaRecorder.state === "recording") {
    mediaRecorder.stop();
    recordButton.textContent = "Start Recording";
  } else {
    recordedChunks = [];
    const stream = video.srcObject;
    mediaRecorder = new MediaRecorder(stream, { mimeType: "video/webm" });
    
    mediaRecorder.ondataavailable = (event) => {
      if (event.data.size > 0) recordedChunks.push(event.data);
    };
    
    mediaRecorder.onstop = () => {
      const recordedBlob = new Blob(recordedChunks, { type: "video/webm" });
      const videoUrl = URL.createObjectURL(recordedBlob);
      downloadVideo.href = videoUrl;
      downloadVideo.style.display = "block";
      downloadVideo.click();
      downloadVideo.style.display = "none";
    };
    
    mediaRecorder.start();
    recordButton.textContent = "Stop Recording";
  }
});

Explanation of Code:

  1. Open WebCam – The getUserMedia API requests access to the WebCam and plays the video stream in the <video> element.
  2. Take Snapshot – When the snapshot button is clicked, the video frame is drawn onto a canvas, and an image file is created for download.
  3. Record Video – Using the MediaRecorder API, the video stream is recorded. Clicking the record button starts recording, and clicking again stops it and saves the video as a downloadable file.

Step 4: Test the Application

Make sure all the files are saved. Now, run your “index.html” in the browser , and follow these steps:

  1. Click Open WebCam to start the video feed.
  2. Click Take Snapshot to capture a still image from the WebCam feed.
  3. Click Start Recording to begin recording the video, then click again to stop and download it.

Conclusion

With just a few lines of JavaScript and HTML, you can access the WebCam, take snapshots, and record video directly from the browser. This functionality can be beneficial for various applications like profile picture capture, video message recording, and more.

P.S.: You read more here about future of React in the field of frontend developer here. React is a JavaScript library to build beautiful user interfaces.

Scroll to Top