2

I have a camera PWA, it's working fine with taking photos and uploading them, but I want to use the rear-facing camera instead of the front facing cam. How do I proceed on doing this?

This is the current lines of coenter code heredes I'm using for initializing the camera and taking the photo. This is on .js

// This will initialize the camera
function initializeMedia() {
  if (!('mediaDevices' in navigator)) {
    navigator.mediaDevices = {};
  }

  if (!('getUserMedia' in navigator.mediaDevices)) {
    navigator.mediaDevices.getUserMedia = function(constraints) {
      var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;

      if (!getUserMedia) {
        return Promise.reject(new Error('getUserMedia is not implemented!'));
      }

      return new Promise(function(resolve, reject) {
        getUserMedia.call(navigator, constraints, resolve, reject);
      });
    }
  }

  navigator.mediaDevices.getUserMedia({
    video: true
  })
  .then(function(stream) {
    videoPlayer.srcObject = stream;
    videoPlayer.style.display = 'block';
  })
  .catch(function(err) {
    imagePicker.style.display = 'block';
  });
}

// capture image
captureButton.addEventListener('click', function(event) {
  canvasElement.style.display = 'block';
  videoPlayer.style.display = 'none';
  captureButton.style.display = 'none';
  var context = canvasElement.getContext('2d');
  context.drawImage(videoPlayer, 0, 0, canvas.width, videoPlayer.videoHeight / (videoPlayer.videoWidth / canvas.width));
  videoPlayer.srcObject.getVideoTracks().forEach(function(track) {
    track.stop();
  });
  picture = dataURItoBlob(canvasElement.toDataURL());
});

1 Answers1

1

You can set video.facingMode to either 'user' for the front camera, or 'environment' for the back camera in the constraints object that you pass to navigator.mediaDevices.getUserMedia().

Example from the MDN:

var constraints = { video: { facingMode: "environment" } };

https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia

Azer
  • 1,200
  • 13
  • 23