Categories
JavaScript Answers

How to Access a Camera from a Browser with JavaScript?

Spread the love

To access a camera from a browser with JavaScript, we can use the WebRTC API to access the camera when permission is granted.

To do this, we write:

const video = document.createElement("video");
video.setAttribute("playsinline", "");
video.setAttribute("autoplay", "");
video.setAttribute("muted", "");
video.style.width = "200px";
video.style.height = "200px";

const facingMode = "user";
const constraints = {
  audio: false,
  video: {
    facingMode
  }
};

navigator.mediaDevices.getUserMedia(constraints).then((stream) => {
  video.srcObject = stream;
});

document.body.appendChild(video);

to create a video element with some attribute with:

const video = document.createElement("video");
video.setAttribute("playsinline", "");
video.setAttribute("autoplay", "");
video.setAttribute("muted", "");
video.style.width = "200px";
video.style.height = "200px";

We set the width, height, autoplay attribute, and more with setAttribute and setting style properties.

Then we call navigator.mediaDevices.getUserMedia with the constraints to access the camera.

audio is set to false to disable picking up audio.

And video.facingMode is set to 'user' to let the code access the front camera.

Once the camera can be accessed, the then callback is run, and the video.srcObject is set to the stream to disable what the camera picks up onto the screen via the video element.

Finally, we call document.body.appendChild with video to display the video element onto the screen.

Now once we granted permission for the code to access the camera, we should see the stuff picked up by the front camera on the browser’s screen.

By John Au-Yeung

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

2 replies on “How to Access a Camera from a Browser with JavaScript?”

Thanks for reading.

Is your site HTTPS and did you enable camera permission on your site?

Leave a Reply

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