GetUserMedia Video and Camera Example

By Stephen Garside on 5/16/2017

If you are looking for an easy example of how to capture input from Video, Web Cams and Cameras using HTML5 and Javascript, then this has never been easier with GetUserMedia.  With just a few lines of code you can prompt your visitors for permission to capture video, here is some example code of how to do it:

var videoCapture = (function ()
{
    var init = function ()
    {
        initCapture();
    }
 
    function initCapture()
    {
        var constraints = { audio: false, video: { width: 1280, height: 720 } };
 
        navigator.mediaDevices.getUserMedia(constraints).then(function (stream)
        {
            var video = document.getElementById('videoCapture');
            video.srcObject = stream;
            video.onloadedmetadata = function (e)
            {
                video.play();
            };
        }).catch(function (err)
        {
            console.log(err);
        });
    }
 
    return {
        Init: init
    }
})();

To get this code snippet to work you will also need to add the following HTML / JS to your page:-

<video id="videoCapture"></video>
<script>
    videoCapture.Init();
</script>

Thats all there is to this easy example of how to capture camera and video input in HTML and JS using GetUserMedia!  At the time of writing this code works in the latest versions of Chrome, Firefox and Edge.  You can also use GetUserMedia to capture microphone input as demonstrated in this easy example.