如何在javascript中切换前置摄像头和后置摄像头?

How to switch between front camera and rear camera in javascript?

let constraints;
function handleVideo(){
const constraints = {
  video: {
    facingMode: {
      exact: 'user'
    }
  }
};

var video;
navigator.mediaDevices.getUserMedia(constraints).
then((stream) => {
  video = document.createElement("video")
  video.srcObject = stream
  video.play()
  video.onloadeddata = () => {
    ctx.height = video.videoHeight
  }
})
}

我知道把exact改成environment可以切换前后摄像头。但是我不知道如何做这个onclick。

Something like this :

function handleVideo(cameraFacing) {
  const constraints = {
    video: {
      facingMode: {
        exact: cameraFacing
      }
    }
  }
  return constraints
};

function turnVideo(constraints) {
  let video;
  navigator.mediaDevices.getUserMedia(constraints)
    .then((stream) => {
      video = document.createElement("video")
      video.srcObject = stream
      video.play()
      video.onloadeddata = () => {
        ctx.height = video.videoHeight
      }
    })

}

document.querySelector(".frontCamera").addEventListener("click", () => {
  turnVideo(handleVideo("user"));
})
document.querySelector(".backCamera").addEventListener("click", () => {
  turnVideo(handleVideo("enviroment"));
})
<div class="frontCamera">front</div>
<div class="backCamera">back</div>