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.)

I hope you like this article and if any doubts please let me know in the comment section.

Subscribe this blog for more such articles.
You can also follow me on Twitter or Linkedin for the latest updates.

Written By:
Saurabh Joshi


Popular Posts