How to Integrate Real-time Webcam on a Web Page Using Javascript

How to Integrate Real-time Webcam on a Web Page Using Javascript

Most websites nowadays offer real-time webcam integration for profile picture upload or any other account verification step.

This tutorial will teach us how to use Vanilla JavaScript to add a webcam to a web page. So let's get this ball rolling.

What is a WebCam

A webcam is a type of video camera that sends or transfers a picture or video progressively in real time to or through a computer network such as the Internet. Webcams can be utilized during a video meeting between two people with live sound and video talks.

What is Javascript

JavaScript is a scripting or programming language that allows you to add advanced functionality to your web pages.

To begin, we should first set up our project.

Please type the command below to launch Visual Studio Code from the terminal.

Then execute:

code.

Note: If you don't have Visual Studio Code installed, you won't be able to use code .

Step 1 - Create a directory

Create a directory and initialize npm by typing the following command:

  • Windows power shell
mkdir jwebcam-with-javascript-demo

cd webcam-with-javascript-demo

npm init -y
  • Linux
mkdir webcam-with-javascript-demo

cd webcam-with-javascript-demo

Step 2 - Create files

Using the commands below, we'll create the script.js and index.html files.

touch index.html script.js

Step 3 - Setting up Index.html

We will setup a simple html base template as show below:

<!DOCTYPE html>
<html lang="en">

<head>
    <title>
        How to Integrate Real-time Webcam on a Web Page Using Javascript
    </title>
</head>

<body>
    <div class="container">
        <div class="card text-center">
            <div class="card-body">
                <h5 class="card-title">How to Integrate Real-time Webcam on a Web Page Using Javascript</h5>
                <div class="video-card">
                    <video id="video" autoplay></video>
                </div>
                <a href="#" class="btn btn-primary">Click Here to Start Cam</a>
                <a href="#" class="btn btn-danger">Click Here to Stop Cam</a>
            </div>
        </div>
    </div>

</body>

</html>

Step 4 - Referencing Script.js, Jquery, Bootstrap JS, and CSS CDN

Although we have added the necessary classes, our application does not appear to be aesthetically pleasing. Instead, let us import the bootstrap CDN and jquery as shown below:

// ...

</title>

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

</head>

// ...

Adding bootstrap js CDN and JQuery

// ...

    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

 <script src="/script.js"></script>

</body>

// ...

Step 5 - Integrating Webcam on the Web Page With Javascript

To gain the user's permission to use the webcam with video track options, we'll use navigator.mediaDevices.getUserMedia. We will specify video: true to indicate that we only want to use the webcam and not the audio.

The function getUserMedia() delivers a promise that resolves when the user grants permission to view the webcam and rejects it when the user denies it. As a result, we used .then and .catch to deal with the promise.

To access and display the camera output in the video tag, let's write the function called startCam as shown below:

// Start Cam function
const startCam = () => {

    //Initialize video
    const video = document.getElementById("video");

    // validate video element
    if (navigator.mediaDevices.getUserMedia) {
        navigator.mediaDevices
            .getUserMedia({ video: true })
            .then((stream) => {
                video.srcObject = stream;
            })
            .catch(function(error) {
                console.log("Something went wrong!");
            });
    }
};

Before Implementing the stopCam function, let's test our startCam function. To do that, let us refer to the startCam function on page load using jquery as shown below:

// ...

$(() => {
    startCam();
});

Step 6 - Adding OnClick Functionality

Let's proceed to index.js to update our button with the text Click Here to Start Cam with onClick attribute using the snippet below:

    <a href="#" class="btn btn-primary" onClick="startCam()">Click Here to Start Cam</a>

Testing our application, we should see a request to accept turning ON our webcam on your browser. We can see how Powerful Javascript is to turn to integrate webcam in our web page.

Step 7 - Implementing Stop Cam

We have seen how super easy it is to integrate a webcam in our web page using javascript, but what about turning the cam OFF? Of course, we should do that with ease, just like we did for turning the webcam ON. Let's stop the video tracks and turn off the webcam when the button stop is clicked.

//  ...

// Stop the webcam function
const stopCam = () => {
    let stream = video.srcObject;
    let tracks = stream.getTracks();
    tracks.forEach((track) => track.stop());
    video.srcObject = null;
};

// ...

Step 8 - Adding OnClick Functionality

Let's proceed to index.js to update our button with the text Click Here to Stop Cam with onClick attribute using the snippet below:

<a href="#" class="btn btn-danger" onClick="stopCam()">Click Here to Stop Cam</a>

Congratulations! We should successfully run our application, start and stop the Web Cam, as shown below.

Screenshot 2021-08-07 at 12.47.09.png

Kindly click here to check the complete code on GitHub.

Conclusion

In this tutorial, we learned about How to integrate WebCam using Javascript on a web page.

Happy coding!

Resources

I'd love to connect with you at Twitter | LinkedIn | GitHub

See you in my next blog article. Take care!!!