Using JavaScript to access your device camera

Hello everyone, in this blog I will show you how to use JavaScript on a web page, and support many browsers without additional libraries to access the current device camera.

How to access the camera

We use JavaScript Media Stream API To access the user's camera (not only on the computer, but also on the mobile phone), this API allows flow To access video and audio captured by the device.

The first step is to check whether the API is supported by the current browser:

if ('mediaDevices' in navigator && 'getUserMedia' in navigator.mediaDevices) {
    // Indicates that the API is supported by the current browser
}

In fact, modern browsers have pretty good support for this API (excluding Internet Explorer, of course)

Capture video stream

To capture the video stream generated by the device, we use the getUserMedia method on the mediaDevices object.

This method receives an object that contains the media type (video or audio) and some requirements. First, we can pass the parameter {video: true} to get video from the camera.

const videoStream = await navigator.mediaDevices.getUserMedia({ video: true })

Executing this statement will require the user to authorize the program to access the camera. If the user refuses, an exception will be thrown and the expected video stream will not be returned. So we have to deal with this in the try/catch syntax block.

Note: this method will return a Promise , so you can have to use async/await or then syntax.

Get other parameters of video stream

We can improve video requirements by delivering the required resolution and minimum and maximum information:

const constraints = {
  video: {
    width: {
      min: 1280,
      ideal: 1920,
      max: 2560,
    },
    height: {
      min: 720,
      ideal: 1080,
      max: 1440,
    },
  },
}

const videoStream = await navigator.mediaDevices.getUserMedia(constraints)

In this way, the video stream enters at the correct ratio of width and height. If it is in portrait mode, you need to reverse the size.

Show video on page

OK, now that we have video streaming, what can we do?

We can display the video on the page through the video element.

// considering there is a
// <video autoplay id="video"></video>
// tag in the page
const video = document.querySelector('#video')
const videoStream = await navigator.mediaDevices.getUserMedia(constraints)
video.srcObject = videoStream

Note: there is an autoplay attribute in the video element, if not, you need to explicitly call video.play() method to display the image

Access front and rear cameras on your phone

The getUserMedia method uses the operating system's default video recording device by default. In a mobile phone with two cameras, it uses a front camera.

In order to access the rear camera, we need to include faceingmode: "environment" when passing video parameters:

const constraints = {
    video: {
        width: { ... },
        height: { ... },
        facingMode: 'environment'
    }
}

The value of the default faceingmode field is' user ', which indicates that it is a front camera

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

videoStream.getTracks().forEach(track => {
    track.stop()
})

Making screenshots

Another cool thing is that you can capture screenshots of the video.

You can draw the current video frame image onto the canvas element as follows:

// considering there is a
// <canvas id="canvas"></canvas>
// tag in the page
const canvas = document.querySelector('#canvas')
canvas.width = video.videoWidth
canvas.height = video.videoHeight
canvas.getContext('2d').drawImage(video, 0, 0)

You can also put the content displayed on the canvas element on an img element.

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

const img = document.createElement('img')
img.src = canvas.toDataURL('image/png')
screenshotContainer.prepend(img)

conclusion

Presentation on page address

Complete source code address

Tags: Javascript Mobile Attribute

Posted on Thu, 11 Jun 2020 03:01:16 -0400 by siminder