简体   繁体   中英

How to select rear-facing camera on a progressive web application?

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());
});

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM