Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading