Categories
JavaScript Answers

How to access camera from a browser with JavaScript?

Spread the love

To access camera from a browser with JavaScript, we use the navigator.mediaDevices.getUserMedia method.

For instance, we write

<video src=""></video>

to add a video element.

Then we write

const front = false;
const video = document.querySelector("video");
const constraints = {
  video: {
    facingMode: front ? "user" : "environment",
    width: 640,
    height: 480,
  },
};

const mediaStream = await navigator.mediaDevices.getUserMedia(constraints);
video.srcObject = mediaStream;
video.onloadedmetadata = (e) => {
  video.play();
};

to select the video element with querySelector.

We get permission for the camera with navigator.mediaDevices.getUserMedia.

And then we set the mediaStream as the src attribute value of the video element if permission is granted.

Finally, we call play to play the captured video.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *