Technology4 min read

Capture Photo using Webcam in Javascript

Abhishek Ahlawat

By Abhishek Ahlawat โ€” Recently

Founder of StudyTonight and a MERN fullstack developer. Writes about JavaScript, web development, Linux, and tech.

Summarize this article using AI

We can use the WebRTC API to capture still photos using the device camera in Javascript. In this tutorial, we will learn how to stream video from webcam or the device's camera, and how to capture a still photo that can be used for any purpose like uploading to the server, etc.

capture photo using javascript

If you are a beginner in Javascript, you can learn Javascript from using our detailed tutorial set.

So, let's not waste any more time and jump into the code implementation.

Capture Photo using the device camera in Javascript

In the HTML code, we will define a section for streaming the video captured from the camera, where the user will see their live video, to pose, and finally capture a photo.

We will have a Take Photo button, which will trigger the photo capturing.

And another section in which we will display the output. In that section, we will have an empty <img> tag, in which we will add the output image.

Here is the HTML code:

<div class="contentarea">
    <h1>
        Using Javascript to capture Photo
    </h1>
    <div class="camera">
        <video id="video">Video stream not available.</video>
    </div>
    <div><button id="startbutton">Take photo</button></div>
    
    <canvas id="canvas"></canvas>
    <div class="output">
        <img id="photo" alt="The screen capture will appear in this box."> 
    </div>
</div>

If you observe the above HTML code, you will see that we have an HTML canvas tag too, well this is where intermediate image frames are stored, before they are converted into an image of proper format to be shown using the <img> tag.

We will keep the canvas tag hidden using CSS, you can see the CSS style rules in the live example snippet at the end. Now let's move to the Javascript code.

Time for some Javascript

The Javascript code is divided into 3 sections.

  1. The basic setup

  2. Clear the photo

  3. Capturing the photo

The Basic setup

The basic startup part which involves initialization of variables, asking the user for permission to access the webcam, then start video streaming from webcam, getting references to all the HTML elements which we will be using in the Javascript code, etc.

We will also handle the video streaming getting started in the video tag defined above in HTML, to adjust the height, width, etc of incoming video.

And we will be adding a click event listener to the Take photo button.

Here's the code for the startup() function:

function startup() {
    video = document.getElementById('video');
    canvas = document.getElementById('canvas');
    photo = document.getElementById('photo');
    startbutton = document.getElementById('startbutton');

    // access video stream from webcam
    navigator.mediaDevices.getUserMedia({
            video: true,
            audio: false
        })
        // on success, stream it in video tag
        .then(function(stream) {
            video.srcObject = stream;
            video.play();
        })
        .catch(function(err) {
            console.log("An error occurred: " + err);
        });

    video.addEventListener('canplay', function(ev) {
        if (!streaming) {
            height = video.videoHeight / (video.videoWidth / width);

            if (isNaN(height)) {
                height = width / (4 / 3);
            }

            video.setAttribute('width', width);
            video.setAttribute('height', height);
            canvas.setAttribute('width', width);
            canvas.setAttribute('height', height);
            streaming = true;
        }
    }, false);

    startbutton.addEventListener('click', function(ev) {
        takepicture();
        ev.preventDefault();
    }, false);

    clearphoto();
}

We will be calling this startup function when the HTML page loads, by adding the following code window.addEventListener('load', startup, false);.

Clearing the Photo

In this, we collect the frames of the photo from the canvas and then convert it into a format like PNG or any other to show it in the HTML page.

function clearphoto() {
    var context = canvas.getContext('2d');
    context.fillStyle = "#AAA";
    context.fillRect(0, 0, canvas.width, canvas.height);

    var data = canvas.toDataURL('image/png');
    photo.setAttribute('src', data);
}

Capturing the Photo

This is the main part where we capture a frame from the video stream.

function takepicture() {
    var context = canvas.getContext('2d');
    if (width && height) {
        canvas.width = width;
        canvas.height = height;
        context.drawImage(video, 0, 0, width, height);

        var data = canvas.toDataURL('image/png');
        photo.setAttribute('src', data);
    } else {
        clearphoto();
    }
}

And we are done. It's time to see the code in action now.

Live Code:

Here is the live code. Click on Run to see the code in action. The first time, you will be asked to give access to your Webcam, so please click on Allow.

Conclusion:

In this tutorial, we used the WebRTC API to capture still photo using the device's camera. This can be used if you are building any application where you have to capture image of the end-user may be to fill some application form, or for photo verification, etc.

You may also like:

Spotted something outdated or wrong?

Liked this? See more StudyTonight posts in Google results.

Add StudyTonight as a preferred source
Next questLIVE OPSStep 2 / 3

Practice real incidents in the browser

System Design Ops โ€” put out fires, ship fixes, and stack XP. Reading done. Time to play.

Play System Design
  • +XP

    Every sim

  • Incidents

    Live ops

  • Ranks

    Climb up

Read next