Solution 1:

Check out https://simpl.info/getusermedia/sources/ that shows how you can select sources using

MediaStreamTrack.getSources(gotSources);

You can then select the source and pass it in as optional into getUserMedia

var constraints = {
  audio: {
    optional: [{sourceId: audioSource}]
  },
  video: {
    optional: [{sourceId: videoSource}]
  }
};
navigator.getUserMedia(constraints, successCallback, errorCallback);

It is now fully available in Stable Chrome and mobile (As of v30)

Solution 2:

A demo can be found at https://webrtc.github.io/samples/src/content/devices/input-output/. This will allow access to both the front and rear camera.

Many demos that you will find rely on the deprecated function:

MediaStreamTrack.getSources() 

As of Chrome 45 and FireFox 39, you will need to use the function:

MediaDevices.enumerateDevices()

Example:

if (!navigator.mediaDevices || !navigator.mediaDevices.enumerateDevices) {
  console.log("enumerateDevices() not supported.");
  return;
}

// List cameras and microphones.

navigator.mediaDevices.enumerateDevices()
  .then(function(devices) {
    devices.forEach(function(device) {
      console.log(device.kind + ": " + device.label +
        " id = " + device.deviceId);
    });
  })
  .catch(function(e) {
    console.log(e.name + ": " + e.message);
  });

Further documentation can be found here: https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/enumerateDevices

Solution 3:

In Chrome on my Samsung S8 I can use "facingMode"="environment" to take video from the 'rear camera'. The default seems to be "user" (the 'front' camera)

in TypeScript:

    const video = document.getElementById("video");
    const constraints = {
        advanced: [{
            facingMode: "environment"
        }]
    };
    navigator.mediaDevices
        .getUserMedia({
            video: constraints
        })
        .then((stream) => {
            video.src = window.URL.createObjectURL(stream);
            video.play();
        });

ref: MediaTrackConstraints/facingMode

Solution 4:

Last time i developped that code, soo here is the version which i use : you call directly the function whichCamera in your code and you specefic which camera "user","environment" or "computer"'if you are runing in a computer)

`//----------------------------------------------------------------------
//  whichCamera(Type)
//    For smartphone or tablet :
//     Start the type={user,environment} camera.
//    For computer it's simple :
//      type = "computer".
//----------------------------------------------------------------------
var streamSrc, cameraType;
function whichCamera(type){

  var cameraFacing;
  cameraType = type;
  if( type == "user")
    cameraFacing = 0;
  else if( type == "environment")
    cameraFacing = 1;
  else if( type == "computer"){
    cameraFacing = 2;
  }
  console.log(type+" index : "+cameraFacing);

  //  Here we list all media devices, in order to choose between
  //  the front and the rear camera.
  //      videoDevices[0] : user Camera
  //      videoDevices[1] : environment Camera
  //  Then set the video resolution.
  navigator.mediaDevices.enumerateDevices()
  .then(devices => {
    var videoDevices, videoDeviceIndex, constraints;
    //  Initialize the array wich will contain all video resources IDs.
    //  Most of devices have two video resources (Front & Rear Camera).
    videoDevices = [0,0];
    //  Simple index to browse the videa resources array (videoDevices).
    videoDeviceIndex = 0;
    //  devices.forEach(), this function will detect all media resources (Audio, Video) of the device
    //  where we run the application.
    devices.forEach(function(device) {
      console.log(device.kind + ": " + device.label +
        " id = " + device.deviceId);
      // If the kind of the media resource is video,
      if (device.kind == "videoinput") {
        //  then we save it on the array videoDevices.
        videoDevices[videoDeviceIndex++] =  device.deviceId;
        console.log(device.deviceId+" = "+videoDevices[videoDeviceIndex-1]);
      }
    });
    console.log("Camera facing ="+cameraFacing+" ID = "+videoDevices[videoDeviceIndex-1]);

    // Here we specified which camera we start,
    //  videoDevices[0] : Front Camera
    //  videoDevices[1] : Back Camera
    if( cameraFacing != "computer"){
      constraints = { deviceId: { exact: videoDevices[cameraFacing]  }};
      return navigator.mediaDevices.getUserMedia({ video:
                                                          constraints,
                                                          width: { min: 1280, ideal: 1600, max: 1920 },
                                                          height: { min: 720, ideal: 1200, max: 1080 }
                                                  }
                                                );
    }else
      return navigator.mediaDevices.getUserMedia({ video: true });
    })
    //  Then we retrieve the link to the video stream.
    .then(stream => {
      if (window.webkitURL) {
        video.src = window.webkitURL.createObjectURL(stream);
        localMediaStream = stream;
        console.log(localMediaStream +" = "+ stream)
      } else if (video.mozSrcObject !== undefined) {
        video.mozSrcObject = stream;
        console.log(video.mozSrcObject +" = "+ stream)
      } else if (video.srcObject !== undefined) {
        video.srcObject = stream;
        console.log(video.srcObject +" = "+ stream)
      } else {
        video.src = stream;
        console.log(video.src +" = "+ stream)
      }
      streamSrc = stream;
    })
    .catch(e => console.error(e));

}