Search code examples
javascriptioscameragetusermedia

Javascript Camera toggle not toggling


I'm looking to toggle a camera (facingMode) from user to environment. The toggle seems to be working in the sense that front is toggling from true to false. However, facingMode in constraints remains environment.

What am I overlooking?

Codepen: https://codepen.io/abenjamin/pen/qYWeXj?editors=1111

var front = false;
document.getElementById('cameraToggle').onclick = function() { front = !front; console.log(constraints) };

var constraints = { video: { facingMode: (front? "user" : "environment") } };

Solution

  • You repeated this line twice in your codepen, once at the top and once at the bottom:

    document.getElementById('cameraToggle').onclick = function() { front = !front; console.log(constraints) };
    

    Another problem is that primitives are referenced by value. If you have let x = 3; const obj = { x }; x = 4;, the object will not change - it will continue to be { x: 3 }.

    What you need to do is update the constraints object itself and then proceed to do whatever you need to do with the mutated object. For example:

    document.getElementById('cameraToggle').onclick = function() {
      front = !front;
      constraints.video.facingMode = front
        ? "user"
        : "environment";
      // interact with the mutated `constraints` object if needed
    };