Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getUserMedia() - selecting rear camera on mobile

Tags:

javascript

This is my question.

I'm making a little app that uses JS-OCR to take a photo and detect a word. It works well, but in I only can user the front camera. My idea is to use only the rear camera, it's not necessary to have an option to switch the cameras.

I was reading about the getUserMedia() function, but I can't solve the problem. This is the piece of code involved (function searchForRearCamera()):

function searchForRearCamera() {
    var deferred = new $.Deferred();

    //         Check that the browser supports getUserMedia.
    // If it doesn't show an alert, otherwise continue.
    if (navigator.getUserMedia) {
        // Request the camera.
        navigator.getUserMedia(
            // Constraints
            {
                video: true
            },

            // Success Callback
            function (localMediaStream) {

            },

            // Error Callback
            function (err) {
                // Log the error to the console.
                console.log('The following error occurred when trying to use getUserMedia: ' + err);
            }
        );

    } else {
        alert('Sorry, your browser does not support getUserMedia');
    }

    //MediaStreamTrack.getSources seams to be supported only by Chrome

    if (MediaStreamTrack && MediaStreamTrack.getSources) {

        MediaStreamTrack.getSources(function (sources) {
            var rearCameraIds = sources.filter(function (source) {
                return (source.kind === 'video' && source.facing === 'environment');
            }).map(function (source) {
                return source.id;
            });

            if (rearCameraIds.length) {
                deferred.resolve(rearCameraIds[0]);
            } else {
                deferred.resolve(null);
            }
        });
    } else {
        deferred.resolve(null);
    }

    return deferred.promise();
}

This is DEMO

like image 999
Joan Subirats Llaveria Avatar asked Dec 02 '25 07:12

Joan Subirats Llaveria


1 Answers

navigator.getUserMedia is long deprecated. Use navigator.mediaDevices.getUserMedia now.

To get the rear camera, you can use the MediaConstraint:video:facingMode property. Available values are 'user' (front camera), and 'environment' (back camera).

navigator.mediaDevices.getUserMedia({
  audio: false,
  video: {
    facingMode: 'environment'
  }
})
  .then(stream => vid.srcObject = stream)
  .catch(console.error);
<video muted autoplay id="vid"></video>

Or as a fiddle since null origin StackSnippet's iframe may block the request to gUM.

like image 200
Kaiido Avatar answered Dec 04 '25 19:12

Kaiido