Home > Net >  How to switch between front camera and rear camera in javascript?
How to switch between front camera and rear camera in javascript?

Time:05-29

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
  }
})
}

I know by changing exact to environment can switch between front and back camera. But I don't know how to do this onclick.

CodePudding user response:

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 >front</div>
<div >back</div>

  • Related