Skip to main content

JavaScript: MediaDevices(Opening webcam to capturing image and downloading it)

In this article, we will see how to open a webcam in chrome and how to capture the image and download it.

So let's start,
We will be using Navigator.mediaDevices which provides access to connected media input
devices like cameras and microphones, as well as screen sharing.
The Navigator object contains information about the browser.
There is no public standard that applies to the navigator object, but all major browsers support it.


<!DOCTYPE html>
  <meta charset='utf-8'>
  <meta http-equiv='X-UA-Compatible' content='IE=edge'>
  <meta name='viewport' content='width=device-width, initial-scale=1'>
  <link rel='stylesheet' type='text/css' media='screen' href='main.css'>
  <script src='video.js'></script>
  <div class='container'>
      <video autoplay></video>
      <p id='prompt1'> Capture Video To Get Started</p>
              <button class='capture'>Capture video</button>
              <button id='screenshot' disabled>Screenshot</button>
              <button class='download' disabled>Download</button>
              <label for="select"> Format </label>
              <select id="select" onchange='onFormatChange()'>
                <option value='.png'>PNG</option>
                <option value='.jpeg'>JPEG</option>
                <option value='.jpg'>JPG</option>
                <option value='.tiff'>TIFF</option>
              <button id='clear' onclick="clearAll()" disabled>Clear All</button>
      <div class='imgContainer'>
          <p id='prompt2'>Click 'Screenshot' to take a picture.</p>
          <img src=''>

Css Code(main.css):

body, button, select{
    font-family: 'Courier New', Courier, monospace;

    display: flex;
    margin: auto;
    justify-content: space-between;
    align-items: center;
    position: relative;

video, .container > .imgContainer{
    display: flex;
    align-items: center;
    width: 45%;
    height: 400px;
    border: solid 1px #6495ED;
    max-width: 600px;
    position: relative;

#prompt1, #prompt2{
    position: absolute;
    top: 50%;
    left: 10px;
    z-index: 100;

    display: none;

.container > div > img {
    width: 100%;
    display: none;

    text-align: center;

button, select, label{
    cursor: pointer;
    display: block;
    margin: 10px auto;
    width: 125px;
    padding: 10px 0 10px 0;

    cursor: not-allowed;

    display: flex;
    justify-content: space-evenly;
    align-items: center;
    width: 300px;
    margin: 10px auto;

select, label{
    visibility: hidden;
    -webkit-appearance: none;
    -webkit-border-radius: 0px;
    border-radius: 0px;
    text-align: center;
    text-align-last: center;
    -moz-text-align-last: center;

    visibility: visible;

JavaScript Code(video.js):

var img, backgroundImage, video, prompt1, prompt2, screenshot, download, select, label, clear;
var enable = false;
const canvas = document.createElement('canvas');
var format = '.png'

const init = () => {
    if (enable){
        prompt1 = document.getElementById('prompt1');
        prompt2 = document.getElementById('prompt2');
        screenshot = document.getElementById('screenshot');
        clear = document.getElementById('clear');
        select = document.getElementsByTagName('select')[0]
        label = document.getElementsByTagName('label')[0]
        img = document.getElementsByTagName('img')[0];
        video = document.getElementsByTagName('video')[0];
        download = document.getElementsByClassName('download')[0]
        download.addEventListener('click', onDownload)
        document.getElementsByClassName('capture')[0].addEventListener('click', onCapture)
        screenshot.addEventListener('click', onScreenshot)

const hasGetUserMedia = () => {
    if (!navigator.mediaDevices && !navigator.mediaDevices.getUserMedia){
        alert('Unable to enable camera.')
    } else {
        enable = true

const onCapture = () => {
                .getUserMedia({video: true})
                .then(stream => {
                    video.srcObject = stream
           = 'none';
           = 'block';
                    screenshot.disabled = false;
                    clear.disabled = false;
                .catch(err=>alert('Error occurred: ' + err));

const onScreenshot = () => {
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;
    canvas.getContext('2d').drawImage(video, 0, 0); = 'none'
    img.src = canvas.toDataURL('image/png'); = 'block'
    download.disabled = false = 'visible' = 'visible'

const onDownload = () => {
    download = document.createElement('a');
    download.href = img.src = 'yourScreenshot' + format; = 'none';

const clearAll = () => {
    video.srcObject.getVideoTracks().forEach(track => track.stop())
    video = document.createElement("video")
    video.autoplay = true
    document.getElementsByClassName('container')[0].insertBefore(video, prompt1)
    if (img){ = 'none'
    screenshot.disabled = true;
    download.disabled = true; = 'hidden'; = 'none';
    format = null; = 'none'; = 'block';
    clear.disabled = true;

document.addEventListener('DOMContentLoaded', init)

So here, firstly init function is called as we have set an event listener for the 'DOMContentLoaded' event. Which check if browser support mediaDevices or not also we had store required element references.

The onCapture method will ask permission for the camera to the user
and once permission is given by the user will set stream to video elements in HTML.

In onScreenshot method we have use canvas.toDataURL() which returns a data URI containing a representation of the image in the format specified by the type parameter (defaults to PNG).
The returned image is in a resolution of 96 dpi. So this method sets the captured image to UI.

In onDownload method we are just doing the download part as we are already storing data URL in onScreenshot method.

That's it no external dependency required.

JsFiddle Link: 
(If there is some permission issue you can copy-paste the code on your machine and run it locally.)

You Might Like:

Node.js interview questions set 1

Node JS: Understanding bin in package.json.

Node.js: Bundling your Node.js application to a single executable for Windows.

Node.js: Extract text from image using Tesseract.


Popular posts from this blog

Node JS:Understanding bin in package.json.

Well as a Node Js developer we know package.json as dependency file where we keep a note of all dependencies of our project. Here we will be looking at what is bin in package.json? To understand this we first need to understand command line application and it's purpose. CLI applications are mostly used to automate things such as deployments of application,running tests,building reports and the list goes on and on. So lets start with creating our first CLI application. First, let’s make sure you have the tools required. To complete this tutorial, you will need the following: 1)A recent version of Node.js downloaded and installed 2)A good text editor, such as Visual Studio Code Next, open your computer’s command prompt (Windows) or terminal (macOS/Linux). Change the current directory to the folder where you save your documents or projects. Enter the following commands to create a new project folder and initialize the project. mkdir hello-cli cd hello-cli npm init Nex

Node.js: Extract text from image using Tesseract.

In this article, we will see how to extract text from images using Tesseract . So let's start with this use-case, Suppose you have 300 screenshot images in your mobile which has an email attribute that you need for some reason like growing your network or for email marketing. To get an email from all these images manually into CSV or excel will take a lot of time. So now we will check how to automate this thing. First, you need to install Tesseract OCR( An optical character recognition engine ) pre-built binary package for a particular OS. I have tested it for Windows 10. For Windows 10, you can install  it from here. For other OS you make check  this link. So once you install Tesseract from windows setup, you also need to set path variable probably, 'C:\Program Files\Tesseract-OCR' to access it from any location. Then you need to install textract library from npm. To read the path of these 300 images we can select all images and can rename it to som

Node.js: Bundling your Node.js application to single executable for Windows.

In this article, we will see how to bundle Node.js application to a single executable for Windows. What's the need? Well recently, I had taken a work where I needed to convert pdf's(Of similar format) to excel sheet. So I was reading the pdf's from a folder in desktop and I was storing the output excel sheet into a separate folder on the desktop. I used Node.js for the program. Now the client wanted it to install the program on 25 windows machine and his budget was really low. So it was also not possible for me to install node.js for 25 machines and then install the required dependency for each one. One of the solution: While I was searching for an easy solution I found this amazing npm module pkg . This module can make your node.js app work like plug and play type. No need to install Node.js on the client machine or any other dependency.  It helps to make a commercial or trial version of your node.js application without exposing the source code. I found