This post is a bit of an update on one of my popular posts from a few years ago – 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:

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:

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:

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:

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

Photo by Cleo Tse on Unsplash