3

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

function start()
 {
  var video = document.getElementById('video'),
  vendorUrl = window.URL;
  navigator.mediaDevices.getUserMedia({
        video: true,
        audio: true
    })
.then(function(stream) {
  video.src = vendorUrl.createObjectURL(stream);
          video.play();
})
.catch(function(err) {
alert("no");
});

};
  • Possible duplicate of [how to make getUserMedia() work on all browsers](https://stackoverflow.com/questions/21015847/how-to-make-getusermedia-work-on-all-browsers) – Sebastian Simon Mar 25 '18 at 08:06

2 Answers2

2

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

    
    function takeSnapshot() {
      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%;
    }
<video autoplay></video>

Copy it to your local and run

Hope this helps you

Rahul Mahadik
  • 11,668
  • 6
  • 41
  • 54
1

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.

Matt
  • 124
  • 12