Captured an Image from Camera with Javascript

4 mins
22 Aug 2023

Back to a simple but useful tutorial article, we will discuss how to captured an image from camera with Javascript and include examples. Javascript is a programming language that is known to be very flexible, it can be run on backend servers (Node.js), frontends (React.js or Vue.js) or even mobile applications with React native. With javascript we can do many things including making this feature take pictures with the browser, some examples that I will give later are with vanilla javascript without any framework and a little explanation about the functions used.

The self-portrait feature is very useful if you have web applications such as online photo editing, identity scanning, registration forms, data collection and many more.



Captured an image from camera with Javascript


1. Preparation

We only provide 1 html file index.html, we do not use additional files such as script.js or style.css, we do this so that it is easier for you to understand. First of all create an html5 document as usual and create some additional elements that are used to display the user's camera, the canvas elements needed to produce the photo, the location of the photo capture and the capture button and simple styling as follows.

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Capture photo with javascript | Genelify</title>
        #video {
          box-shadow: 2px 2px 3px black;
          width: 320px;
          height: 240px;
        #photo {
          box-shadow: 2px 2px 3px black;
          width: 320px;
          height: 240px;
        #canvas {
          display: none;
        .camera {
          width: 340px;
          display: inline-block;
        .output {
          width: 340px;
          display: inline-block;
          vertical-align: top;
        #startbutton {
          display: block;
          position: relative;
          margin: 0 auto;
          bottom: 32px;
          background-color: rgba(0, 150, 0, 0.5);
          box-shadow: 0px 0px 1px 2px rgba(0, 0, 0, 0.2);
          font-size: 14px;
          color: rgba(255, 255, 255, 1);
        .content-area {
          font-size: 16px;
          width: 760px;
    <div class="content">
        <div class="camera">
          <video id="video">Stream not available.</video>
          <button id="capture">Take photo</button>
        <canvas id="canvas"></canvas>
        <div class="output">
          <img id="photo"/>
        // Put the javascript code here


2. Displays the camera of the user's device

After we have finished creating the index.html file, then we will create a javascript script to display the camera, process the image onto the canvas and take a photo button. From these elements we will save them into each variable by using the id as an element marker and determining how wide the image will be later, you can adjust it according to your wishes. Add this javascript syntax before closing body tag.

const width = 640; 
let height = 0;
let video = document.getElementById("video");
let canvas = document.getElementById("canvas");
let photo = document.getElementById("photo");
let capture = document.getElementById("capture");

Next is the most important, we will use the method from JavaScript: getUserMedia() which functions to communicate with the user's camera device, getUserMedia() can function properly with smartphone cameras and webcam on computers/laptops when taking pictures or videos, here is the syntax.

navigator.mediaDevices.getUserMedia({ video: true, audio: false }).then((stream) => {
    video.srcObject = stream;;
.catch((err) => {

In the getUserMedia() parameter we set video as true and audio as false, video must be true because to run the camera device itself and audio as false because we don't need it, taking photos is not possible with audio right? and when executing it, getUserMedia will produce a Promise, the stream results from the camera being run, will be inserted into the video object element to be displayed in the browser with the syntax: video.srcObject = stream and to run the camera stream.

In addition, we know that the average smartphone currently has 2 cameras, the front and rear cameras, the JavaScript method by default will use the front camera as the media for taking pictures from the user's device, that's because in the previous parameters we set video as true, but if you want to use the rear camera on a smartphone, you need to change the video parameter to "environment" or more in this syntax.

navigator.mediaDevices.getUserMedia({ video : { FacingMode: { exact: "environment" } }, audio: false })


3. Set the width and height of the camera

Next we will create a script to determine the size of the width and height of the stream canvas automatically, the results of the width and height will be processed based on the width we have previously determined const width = 640 and the results of the height and width of the canvas will be calculated based on the width specified determined by the variable width, this aims so that the expected photo results are not flat. Below is the syntax for processing the canvas size automatically.

video.addEventListener("canplay", function ()
    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);
}, false);

Unlike other events like click or change, the canplay event (HTMLMediaElement) instructs the browser to start playing media such as video and audio. According to Mozilla's documentation, this event cannot be stopped unless you use the pause() or stop() method on the targeted element. Okay, then we will enter the final stage.


4. Capturing image

At this stage we will process the results from the stream into an image, this process is actually simple, when all the devices and sizes of the canvas are suitable, we only process them using the method from javascript: getContext() and drawImage() and it will be converted into PNG format. as a result of the image extension, you can change it to your liking such as image/jpeg, image/webp and others, the results of this processing we will save into the img element with the photo id as the resulting image. Here is the syntax for the image capture process.

capture.addEventListener("click", function (event)
    const context = canvas.getContext("2d");

    if (width && height)
        canvas.width = width;
        canvas.height = height;
        context.drawImage(video, 0, 0, width, height);

        const data = canvas.toDataURL("image/png");
        photo.setAttribute("src", data);

}, false);

When taking pictures, we use video.pause() this is intended so that the results of taking pictures are not blurry and in focus, when capturing process is finished, we can run the user's camera device again with at the end of the syntax.



Finally, we have finished creating a simple image capture feature with the default method from JavaScript getUserMedia(), according to the official Mozilla documentation, this JavaScript built-in method works in almost all modern browsers and you can change the above syntax to your own style.