Javascript后置摄像头

时间:2018-07-26 17:43:17

标签: javascript android html5 camera

您好,我正在尝试使用此演示 https://kdzwinel.github.io/JS-OCR-demo/

但是我只得到手机的前置摄像头,它使用此代码启用摄像头

             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();
}

我尝试添加代码以从https://simpl.info/getusermedia/sources/

中选择摄像机

但是没有任何成功:(感谢所有人,我如何在第一个示例中轻松使用后置摄像头

1 个答案:

答案 0 :(得分:1)

以下内容可在Firefox和Chrome中发挥作用

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

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

此处演示:https://js-1lq5ue.stackblitz.io/