Capturing an image from your webcam using JavaScript

This post is a bit of an update on one of my popular posts from a few years ago – https://www.purplesquirrels.com.au/2013/08/webcam-to-canvas-or-data-uri-with-html5-and-javascript/

I thought I’d do an updated post on how to get an image from webcam using current web APIs. This time we’ll be using the Media Stream API.

To start off, we need to create a couple of HTML elements – a button and an img tag:

<button id="takephoto">Take Photo</button> 
<img id="img" />

For the JavaScript we’ll start by getting the video devices that are available:


1
2
3
4
5
6
7
let mediaStream;

try {
    mediaStream = await navigator.mediaDevices.getUserMedia({ video: true })
} catch (error) {
    console.error('getUserMedia() error:', error)
}

Then we get the first video track and create an ImageCapture object:


1
2
3
const tracks = mediaStream.getVideoTracks();
const mediaStreamTrack = tracks[0];
const imageCapture = new ImageCapture(mediaStreamTrack);

We can now add a click handler to the button which takes the image from the camera and sets it as the source to the img element:


1
2
3
4
5
6
7
8
9
10
11
12
13
const img = document.getElementById("#img");
const button = document.getElementById("#takephoto");

button.addEventListener("click", async e => {
    try {
        let blob = await imageCapture.takePhoto();

        img.src = URL.createObjectURL(blob);
        img.onload = () => URL.revokeObjectURL(this.src);
    } catch (error) {
        console.error('takePhoto() error:', error);
    }
});

You could also draw the above image to a canvas element:


1
2
const canvas = document.getElementById("#canvas");
canvas.getContext("2d").drawImage(img, 0, 0);

Photo by Cleo Tse on Unsplash

Posted toJavascript