Skip to content Skip to sidebar Skip to footer

Accessing Device Camera Using Javascript

I want to access my device camera using javascript . But this code only works in firefox and that too on desktop . I want to access my camera on other browsers as well as mobile de

Solution 1:

  (function() {
    'use strict';
    var video = document.querySelector('video')
      , canvas;

    
    functiontakeSnapshot() {
      var img = document.querySelector('img') || document.createElement('img');
      var context;
      var width = video.offsetWidth
        , height = video.offsetHeight;

      canvas = canvas || document.createElement('canvas');
      canvas.width = width;
      canvas.height = height;

      context = canvas.getContext('2d');
      context.drawImage(video, 0, 0, width, height);

      img.src = canvas.toDataURL('image/png');
      document.body.appendChild(img);
    }

    
    if (navigator.mediaDevices) {
      // access the web cam
      navigator.mediaDevices.getUserMedia({video: true})
     
        .then(function(stream) {
         
		  video.srcObject = stream
          video.addEventListener('click', takeSnapshot);
        })
      
        .catch(function(error) {
          document.body.textContent = 'Could not access the camera. Error: ' + error.name;
        });
    }
  })();
video, img {
      max-width:100%;
    }
<videoautoplay></video>

Copy it to your local and run

Hope this helps you

Solution 2:

Mobile browsers need a valid click event to start playing video, so video.play() will not work on mobile until it receives this. Just add a play icon over the video (only on mobile) to induce the user to click, and bind video.play() to this click event.

Post a Comment for "Accessing Device Camera Using Javascript"