In this article, I’ll show you how to access your device’s camera on a Web page through JavaScript and support multiple browsers without external libraries.

How do I use the camera API

To access the user’s camera (or microphone), we use the JavaScript MediaStream API. The API allows streaming access to video and audio captured by these devices.

The first step is to check if the browser supports the API:

if (
  "mediaDevices" in navigator &&
  "getUserMedia" in navigator.mediaDevices
) {
  // ok, browsers support it
}
Copy the code

In modern browsers, support is good (not Internet Explorer, of course).

Capture the video stream

To capture the video stream generated by the camera, we use the getUserMedia method of the mediaDevices object. This method receives an object containing the type of media (video or audio) we are requesting and some requirements. First, we can use {video: true} to get the video of the camera.

const videoStream = await navigator.mediaDevices.getUserMedia({ video: true });
Copy the code

This call will ask the user whether to allow access to the camera. If the user refuses, it throws an exception and does not return the stream. Therefore, the handling of this case must be done within a try/catch block.

Note that it returns a Promise, so you must use async/await or then blocks. Authorization also pops up on Mac OS systems

Click “OK” to access the computer camera, the console output videoStream object is as follows

Video Requirements

We can improve video requirements by passing information about the required resolution and minimum and maximum limits:

const constraints = {
  video: {
    width: {
      min: 1280.ideal: 1920.max: 2560,},height: {
      min: 720.ideal: 1080.max: 1440,}}};const videoStream = await navigator.mediaDevices.getUserMedia(constraints);
Copy the code

This way, the stream enters with the correct ratio of width to height, which would require size inversion if it was a phone in portrait mode.

Displays the video on the page

Now that we have the flow, what do we do with it?

We can display the video in the Video element on the page:

// There is a 
       tag
const video = document.querySelector("#video");
const videoStream = await navigator.mediaDevices.getUserMedia(constraints);
video.srcObject = videoStream;
Copy the code

Note the autoplay property in the Video TAB, without which you need to call Video.play () to actually start displaying the image.

Access the phone’s front and rear cameras

By default, getUserMedia will use the system’s default video recording device. If it’s a phone with two cameras, it uses a front-facing camera.

To access the rear camera, we must include faceModeMode:”environment” in the video specification:

const constraints = {
  video: {
    width: {... },height: {... },facingMode: "environment"}};Copy the code

The default is faceingMode:”user”, which means front-facing camera.

Note that if you want to change the camera while the video is already playing, you need to stop the current video stream and then replace it with another camera’s video stream.

videoStream.getTracks().forEach((track) = > {
  track.stop();
});
Copy the code

screenshots

Another cool thing you can do is capture an image (screen shot) of the video.

You can draw the current video frame on the Canvas, for example:

// The page has a 
       tag
const canvas = document.querySelector("#canvas");
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
canvas.getContext("2d").drawImage(video, 0.0);
Copy the code

You can also display canvas content in the IMG element.

In the example created in this tutorial, I added a button that dynamically creates an image from a canvas and adds it to a page:

const img = document.createElement("img");
img.src = canvas.toDataURL("image/png");
screenshotsContainer.prepend(img);
Copy the code

Complete examples and code

Online effect and the source code: coding. Zhangbing. Site/the HTML? U…


This article is published on the public account “Front-end full stack Developer” ID: BY-Zhangbing-dev, the first time to read the latest article, will be published two days before the new article. After concern private letter reply: gift package, send some network high-quality video course network disk information, can save a lot of money for you!