简体   繁体   中英

Rear camera on mobile using HTML5 / JS

Finally I have a working script which enables me to access camera both on desktop on mobile. However on mobile I would like to use the rear camera primarily.

I tried with facingMode: environment, but it doesn't work.

Here is the link to jsfiddle and the code I have:

     function startcam() {

        // Grab elements, create settings, etc.
        var video = document.getElementById('video');
        var mediaConfig =  { video: true };
        var errBack = function(e) {
            console.log('An error has occurred!', e)
        };

        // Put video listeners into place
        if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
            navigator.mediaDevices.getUserMedia(mediaConfig).then(function(stream) {
                video.src = window.URL.createObjectURL(stream);
                video.play();
            });
        }

        /* Legacy code below! */
        else if(navigator.getUserMedia) { // Standard
            navigator.getUserMedia(mediaConfig, function(stream) {
                video.src = stream;
                video.play();
            }, errBack);
        } else if(navigator.webkitGetUserMedia) { // WebKit-prefixed
            navigator.webkitGetUserMedia(mediaConfig, function(stream){
                video.src = window.webkitURL.createObjectURL(stream);
                video.play();
            }, errBack);
        } else if(navigator.mozGetUserMedia) { // Mozilla-prefixed
            navigator.mozGetUserMedia(mediaConfig, function(stream){
                video.src = window.URL.createObjectURL(stream);
                video.play();
            }, errBack);
        };

 };
 startcam();

Any help would be much appreciated.

This works well in chrome for android

navigator.mediaDevices.getUserMedia({ 
  video: { 
    facingMode: { exact: "environment" }
  } 
})
.then(function(stream) {
  video.src = window.URL.createObjectURL(stream);
  video.play();
});

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