Hemanth.HM

A Computer Polyglot, CLI + WEB ♥'r.

Switch Cameras getUserMedia

| Comments

It statred with a simple tweet:

@_zouhir suggested facingMode

Which has the below mods:

  • "user": The video source is facing toward the user; this includes, for example, the front-facing camera on a smartphone.

  • "environment": The video source is facing away from the user, thereby viewing their environment. This is the back camera on a smartphone.

  • "left": The video source is facing toward the user but to their left, such as a camera aimed toward the user but over their left shoulder.

  • "right": The video source is facing toward the user but to their right, such as a camera aimed toward the user but over their right shoulder.

Here is some simple code to flip cameras:

Check if the browser supports facingMODE

1
2
3
4
let supports = navigator.mediaDevices.getSupportedConstraints();
if( supports['facingMode'] === true ) {
  flipBtn.disabled = false;
}

Set options for the getUserMedia

1
2
3
4
5
6
7
8
let shouldFaceUser = true; //Default is the front cam
let opts = {
  audio: true,
  video: true,
  {
    facingMode: shouldFaceUser ? 'user' : 'environment'
  }
}

Stream the video:

1
2
3
4
5
(async () => {
  const stream = await navigator.mediaDevices.getUserMedia(opts);
  videoElm.srcObject = stream;
  videoElm.play();
})();

Toggle cams:

1
2
3
4
5
6
7
8
flipBtn.addEventListener('click', function(){
  // we need to flip, stop everything
  videoElm.pause()
  videoElm.srcObject = null
  // toggle \ flip
  shouldFaceUser = !shouldFaceUser;
  capture();
})

Demo:

Comments