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

Globant part 1

 1)call,apply,bind example? Ans: a. call Method: The call method is used to call a function with a given this value and arguments provided individually. Javascript code: function greet(name) {   console.log(`Hello, ${name}! I am ${this.role}.`); } const person = {   role: 'developer' }; greet.call(person, 'Alice'); // Output: Hello, Alice! I am developer. In this example, call invokes the greet function with person as the this value and passes 'Alice' as an argument. b. apply Method: The apply method is similar to call, but it accepts arguments as an array. Javascript code: function introduce(language1, language2) {   console.log(`I can code in ${language1} and ${language2}. I am ${this.name}.`); } const coder = {   name: 'Bob' }; introduce.apply(coder, ['JavaScript', 'Python']); // Output: I can code in JavaScript and Python. I am Bob. Here, apply is used to invoke introduce with coder as this and an array ['JavaScript', 'Pyt...

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

CSS INTERVIEW QUESTIONS SET 2

  You make also like this CSS interview question set 1. Let's begin with set 2, 5)What is the difference between opacity 0 vs display none vs visibility hidden? Property           | occupies space | consumes clicks | +--------------------+----------------+-----------------+ | opacity: 0         |        yes      |        yes       | +--------------------+----------------+-----------------+ | visibility: hidden |        yes       |        no        | +--------------------+----------------+-----------------+ | display: none      |        no       |        no        | When we say it consumes click, that means it also consumes other pointer-events like onmousedown,onmousemove, etc. In e...