简体   繁体   中英

Force rear camera on mobile device?

Trying to connect Instascan QR code scanner to AR.js . Everything is okay, but the front camera on the phone turns on and it does not work to switch it to the back. Libraries separately work with the back cameras and allow you to switch, and together only the first one is turned on. Chrome browser does not allow you to select a camera when you open the page, so the problem is relevant, primarily for him.

Code example: Codepen , MediaTrackSettings

<html>
  <head>
    <script src="https://rawgit.com/schmich/instascan-builds/master/instascan.min.js"></script>
    <script src="https://aframe.io/releases/1.0.3/aframe.min.js"></script>
    <script src="https://raw.githack.com/jeromeetienne/AR.js/2.2.2/aframe/build/aframe-ar.js"></script> 
  </head>
  <body>
    <a-scene>
        <a-entity camera></a-entity>
    </a-scene>
 </body>
</html>
// Instascan QR scanner
let scanner = new Instascan.Scanner(
  {
    video: document.getElementById('arjs-video')
  }
);
scanner.addListener('scan', function(content) {
  alert('Content: ' + content);
  window.open(content, "_blank");
});

// Instascan camera switch
Instascan.Camera.getCameras().then(function (cameras) {
  if (cameras.length > 1) {
    scanner.start(cameras[cameras.length - 1]);
  } else {
    scanner.start(cameras[0]);
  }
}).catch(function (e) {
  console.error(e);
});

// MediaTrackSettings
let supports = navigator.mediaDevices.getSupportedConstraints();
if (supports["facingMode"]) {
    alert('Not Support!');
} else {
  let constraints = {
    facingMode: { exact: "environment" }
};
myTrack.applyConstraints(constraints);

This is what worked for me. I tested this on my Microsoft Surface and an Android phone.

        //Detect user's cameras
        Instascan.Camera.getCameras().then(function (cameras) {
            //If a camera is detected
            if (cameras.length > 0) {
                //If the user has a rear/back camera
                if (cameras[1]) {
                    //use that by default
                    scanner.start(cameras[1]);
                } else {
                    //else use front camera
                    scanner.start(cameras[0]);
                }
            } else {
                //if no cameras are detected give error
                console.error('No cameras found.');
            }
        }).catch(function (e) {
            console.error(e);
        });   

I did not include the MediaTrackSettings and did not have any issues.

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