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.

HTML CODE:

<!DOCTYPE html>
<html>
<head>
  <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>
</head>
<body>
  <div class='container'>
      <video autoplay></video>
      <p id='prompt1'> Capture Video To Get Started</p>
          <div>
            <h3>Screenshotter</h3>
              <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>
              </select>
              <button id='clear' onclick="clearAll()" disabled>Clear All</button>
          </div>
      <div class='imgContainer'>
          <p id='prompt2'>Click 'Screenshot' to take a picture.</p>
          <img src=''>
      </div>
  </div>
  <br/>
</body>
</html>


Css Code(main.css):

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

.container{
    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;
}

#prompt2{
    display: none;
}

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

h3{
    text-align: center;
}

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

button:disabled{
    cursor: not-allowed;
}

#buttonContainer{
    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;
}

#c2Label{
    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 = () => {
    hasGetUserMedia()
    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 = () => {
    navigator.mediaDevices
                .getUserMedia({video: true})
                .then(stream => {
                    video.srcObject = stream
                    prompt1.style.display = 'none';
                    prompt2.style.display = '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);
    prompt2.style.display = 'none'
    img.src = canvas.toDataURL('image/png');
    img.style.display = 'block'
    download.disabled = false
    select.style.visibility = 'visible'
    label.style.visibility = 'visible'
}

const onDownload = () => {
    download = document.createElement('a');
    download.href = img.src
    download.download = 'yourScreenshot' + format;
    download.style.display = 'none';
    document.body.appendChild(download);
    download.click();
    document.body.removeChild(download);
};

const clearAll = () => {
    video.srcObject.getVideoTracks().forEach(track => track.stop())
    document.getElementsByClassName('container')[0].removeChild(video);
    video = document.createElement("video")
    video.autoplay = true
    document.getElementsByClassName('container')[0].insertBefore(video, prompt1)
    if (img){
        img.style.display = 'none'
    }
    screenshot.disabled = true;
    download.disabled = true;
    select.style.visibility = 'hidden';
    label.style.display = 'none';
    format = null;
    prompt2.style.display = 'none';
    prompt1.style.display = '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: https://jsfiddle.net/joshiisaurabh/hzntqLeg/1/ 
(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.





Comments

Popular posts from this blog

Coding Interview Questions Set 1

From this article, I will be sharing with you all a series of articles on coding interview questions. So please stay connected for the latest set of questions. It will be a good brainstorming exercise and will also prepare you for coding interviews and will definitely boost your confidence. So let's start, 1)Reverse of a string with only O(1) extra memory. Solution: var reverse = function(string) {     let result = ''     for(let i= string.length -1; i >= 0; i--){         result += string[i];     }     return result; }; 2)Fizz Buzz: Write a program that will accept a number n and will output number till n but for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”. Solution: var fizzBuzz= function(n) {     const arr=[]     for(i=1; i<=n; i++){ ...

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