WebRTC - Selecting the main camera in a webapp (when the device has multiple back cameras)

Viewed 476

Trying to create a web app that captures images from the browser from the back camera, and struggling to locate the main camera in a multi-camera device.

The problem we are facing is that every manufacturer has different naming conventions, and the order of the cameras in the list is not indicative of which camera is the main camera (the one that doesn't have anything special, like wide-angle, or telephoto, periscope, ...) which has the highest resolution.

When using this website: https://webrtc.github.io/samples/src/content/devices/input-output/ for my device, for example, the main camera can be located by selecting either camera 2 2 or camera 2 0: Camera 2 2 and Camera 2 0

Is there any way to locate the main camera using javascript? or at least get camera characteristics programmatically to select the right one?

1 Answers

I'm not sure if WebRTC API has any information about which one is the "main" camera but you can use the constraints while calling the getUserMedia to specify the back camera (the one facing away from the user). This should fetch you the back camera it finds first, in the available mediaDevices which in most cases is the "main" camera.

Specify facingMode as environment to choose the back camera. Read more about facingMode values here.

var constraints = {
  facingMode: { exact: "environment" }
  // add any other constraint you want here
};

navigator.mediaDevices.getUserMedia(constraints)
.then(function(stream) {
  /* use the stream */
})
.catch(function(err) {
  /* handle the error */
});
Related