1

我有一个相机 PWA,它可以很好地拍照和上传照片,但我想使用后置摄像头而不是前置摄像头。我该如何继续这样做?

这是我用于初始化相机和拍照的当前中心代码行。这是在 .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());
});
4

1 回答 1

0

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

于 2019-06-10T04:30:29.347 回答