Take photo from a webcam using JavaScript

Do you want to capture photos from your web-camera and generate images in any supported format e.g. PNG, JPEG, GIF, WebP etc.?

First method, capture photo using Canvas2D API:

Live demo: https://www.webrtc-experiment.com/takePhoto/

Below example captures photo from an HTML5 Video element:

var yourVideoElement = document.querySelector('video');

// pass your HTML5 Video Element
var photo = takePhoto(yourVideoElement);
window.open(photo);

function takePhoto(video) {
    var canvas = document.createElement('canvas');
    canvas.width = video.videoWidth || video.clientWidth;
    canvas.height = video.videoHeight || video.clientHeight;

    var context = canvas.getContext('2d');
    context.drawImage(video, 0, 0, canvas.width, canvas.height);

    return canvas.toDataURL('image/png');
}

Above code returns PNG. Here is how to get different formats:

var PNG = canvas.toDataURL('image/png');
var JPEG = canvas.toDataURL('image/jpeg');
var GIF = canvas.toDataURL('image/gif');
var WebP = canvas.toDataURL('image/webp', 1);


Second method, capture photo using "ImageCapture" API:

Live Demo: https://www.webrtc-experiment.com/ImageCapture/

You need to pass MediaStreamTrack (aka Video-Track) object:

if (typeof ImageCapture === 'function') {
    var firstVideoTrack = yourCameraStream.getVideoTracks()[0];
    var imageCapture = new ImageCapture(firstVideoTrack);
    imageCapture.takePhoto().then(function(blob) {
        var photo = URL.createObjectURL(blob);
        window.open(photo);
    });
}

Note: ImageCapture API requires Chrome version >= 60.