简体   繁体   中英

Javascript Rear Camera

Hi there I'm trying to use this demo https://kdzwinel.github.io/JS-OCR-demo/

But I'm getting only the phone's front camera, it uses this code to enable the camera

             function setupVideo(rearCameraId) {
    var deferred = new $.Deferred();
    var getUserMedia = Modernizr.prefixed('getUserMedia', navigator);
    var videoSettings = {
        video: {
            optional: [
                {
                    width: {min: pictureWidth}
                },
                {
                    height: {min: pictureHeight}
                }
            ]
        }
    };

    //if rear camera is available - use it
    if (rearCameraId) {
        videoSettings.video.optional.push({
            sourceId: rearCameraId
        });
    }

    getUserMedia(videoSettings, function (stream) {
        //Setup the video stream
        video.src = window.URL.createObjectURL(stream);

        window.stream = stream;

        video.addEventListener("loadedmetadata", function (e) {
            //get video width and height as it might be different than we requested
            pictureWidth = this.videoWidth;
            pictureHeight = this.videoHeight;

            if (!pictureWidth && !pictureHeight) {
                //firefox fails to deliver info about video size on time (issue #926753), we have to wait
                var waitingForSize = setInterval(function () {
                    if (video.videoWidth && video.videoHeight) {
                        pictureWidth = video.videoWidth;
                        pictureHeight = video.videoHeight;

                        clearInterval(waitingForSize);
                        deferred.resolve();
                    }
                }, 100);
            } else {
                deferred.resolve();
            }
        }, false);
    }, function () {
        deferred.reject('There is no access to your camera, have you denied it?');
    });

    return deferred.promise();
}

And I've tried to add the code to select the camera from https://simpl.info/getusermedia/sources/

But without any success :( how can I get to use the rear camera in the first example without too much hassle, thanks to all

The following does the trick in both Firefox and Chrome

const constraints = {
 "video": {
   "facingMode": 
      { "ideal": "environment" }
  }
};

const stream = await navigator.mediaDevices.getUserMedia(constraints);

Demo here : https://js-1lq5ue.stackblitz.io/

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