How to use back camera instead of the front camera?

10,332

Solution 1

If you want to force the device to use front camera you can add facingMode in constraints:

var constraints = { 
  audio: true,
  video: {
    facingMode: 'environment'
};

or use exact:

facingMode: { exact: 'environment' }

Solution 2

You can use MediaStreamTrack.getSources(callback) to get all media sources and their id's. With other properties you can filter to check is it audio video or filter by name. Once you know id of media source you want to show, use it to attach it to video tag.

This is good example:
https://simpl.info/getusermedia/sources/
https://github.com/samdutton/simpl/blob/master/getusermedia/sources/js/main.js

Share:
10,332
d00nn12
Author by

d00nn12

Updated on June 25, 2022

Comments

  • d00nn12
    d00nn12 almost 2 years

    I have a QR scanning camera, but when I open my website on a cell phone, the face camera turns on in my website. I want to use the back camera.

    function setwebcam()
    {
    
     var constraints = { audio: true, video: true };
    
    
    
    
    document.getElementById("result").innerHTML="- scanning -";
    if(stype==1)
    {
        setTimeout(captureToCanvas, 500);    
        return;
    }
    var n=navigator;
    document.getElementById("outdiv").innerHTML = vidhtml;
    v=document.getElementById("v");
    
    if(n.getUserMedia)
        n.getUserMedia(constraints, success, error);
    else
    if(n.webkitGetUserMedia)
    {
        webkit=true;
        n.webkitGetUserMedia(constraints, success, error);
    }
    else
    if(n.mozGetUserMedia)
    {
        moz=true;
        n.mozGetUserMedia(constraints, success, error);
    }