HTML5

HTML5 Web Camera Example

In this article I’ll present you how to use and access the visitor Web Camera.

First we will present the API, then we will see an example to explain the HTML5 API usage.
 
 
 
 
 
 
 

1. The history

The specification of the API that allows web pages to interact with user (visitor) camera (and/or microphone) evolved many times.

The story of accessing the user device started with the use of the html <input type="file" /> element and two attributes :

  • accept, this attribute allow to define which type of file the user can upload : <input
    type="file" accept="image/*;" >
  • capture, this attribute tells the browser to capture the media directly from a device.

So at this age, the way you could retreive some data from the user device (camera, or microphone) was to handle the change event on the <input type="file" /> element, and to pass the file to the “good” element, canvas for video rendering, or an image element for image visualisation.

The example below is inspired from the main Specification :

<input type="file" accept="video/*" capture>
<canvas></canvas>

And the JavaScript


var input = document.querySelector('input[type=file]');

input.addEventListener('change', function () {
    var file = input.files[0];
    drawOnCanvas(file);
};

function drawOnCanvas(file) {

   // We use the File APi to read the content of the input file element
   var reader = new FileReader();

    // On reader load with parse the content and draw it on Canvas
    reader.onload = function (e) {
        var dataURL = e.target.result,
            c = document.querySelector('canvas'),
            ctx = c.getContext('2d'),
            img = new Image();

        img.onload = function() {
            c.width = img.width;
            c.height = img.height;
            ctx.drawImage(img, 0, 0);
        };

        img.src = dataURL;
    };

    // Load the file in reader ...
    reader.readAsDataURL(file);
}

This example uses the HTML File API to read, parse and display the video.

Note: This implementation is not really supported anymore by browsers (on desktop), the
would prefer the use of navigator.gerUserMedia().

2. The navigator.getUserMedia()

As with many of the HTML5 features, browser implementation may not be available in the user browser, so first we will need to check if we can use the particular feature.

2.1 Detect the feature …

All browsers created a specific function which can be used to retrieve the user media so we will need to create a wrapper function for accessing the user media :

    function userMedia(){
        return navigator.getUserMedia = navigator.getUserMedia   ||
                                    navigator.webkitGetUserMedia ||
                                    navigator.mozGetUserMedia    ||
                                    navigator.msGetUserMedia     || null;

        }

    ;

    // Now we can use it
    if( userMedia() {
        // We can use the usermedia
    } else {
        // We can not use the user media.
    }

The function userMedia() is used to check if the browser accepts the use of the user device. If it’s supported, the browser prefixed function, is assigned to the navigator.gerUserMedia(). Let see how to use the API.

2.2 The API

The navigator.gerUserMedia() accepts three parameters :

  • constraints, this parameter is required, and must be an object (a
    MediaStreamConstraints object). This object is a simple Object with two members :

                {
                    audio:true, // A boolean to define if we need to access audio device
                    video:true // A boolean to define if we need to acces the video device
                }
            
  • success, this is a required parameter, and it must be a Function, that will be called if the after accessing the device(s).
  • error, this is an optional parameter, and if presents must be a Function, that will be called in case of errors while accessing the device(s).

Note: call to navigator.gerUserMedia() will prompt the user to accept (or not) the use of his device. The success callback, will be called just after the user accept. And the error function is called when error arrived or when the user does not accept the use of his device.

2.3 The Constraints object

The Constraints object can be augmented to define more prerequisites on capturing video (such as video quality).

The constraint is a MediaTrackConstraints object, define in the API.

For example if you only want to capture HD video you can define those constraints :

var hdVideoConstraints = {
  video: {
    mandatory: {
      minWidth: 1280,
      minHeight: 720
    }
  }
};

The MediaTrackConstraints API will allow you to add constraints on elements like aspectRatio or frameRate or even volume. Have a look to the API definition to check how to use those constraints.

Remember the API is still in Draft …

3. Display the Video

This example will display the video from the user webcam in the document :

The HTML file :

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Get User Media - example 1</title>
</head>
<body>
<video id="v"></video>
</body>
</html>

And the javascript.

(function(){
    function userMedia(){
        return navigator.getUserMedia = navigator.getUserMedia ||
        navigator.webkitGetUserMedia ||
        navigator.mozGetUserMedia ||
        navigator.msGetUserMedia || null;

    }

    // Now we can use it
    if( userMedia() ){

        var constraints = {
            video: true,
            audio:false
        };

        var media = navigator.getUserMedia(constraints, function(stream){
            var v = document.getElementById('v');

            // URL Object is different in WebKit
            var url = window.URL || window.webkitURL;

            // create the url and set the source of the video element
            v.src = url ? url.createObjectURL(stream) : stream;

            // Start the video
            v.play();
        }, function(error){
            console.log("ERROR");
            console.log(error);
        });
    } else {
        console.log("Browser does not support WebCam integration");
    }
})();

This will example is quite simple, and the code seems to be self documented.

4. Take A picture

As we used the camera to display the video, we can also use it in order to take some pictures.

In order to take a screenshot of the video we will have to use the canvas Api, lets see the example.

4.1 The Html

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Get User Media - Photo</title>
</head>
<body>
<button id="take">Take a photo</button><br />
<video id="v"></video>
<canvas id="canvas" style="display:none;"></canvas>
<img src="http://placehold.it/300&text=Your%20image%20here%20..." id="photo" alt="photo">
</body>
</html>

I just added button, to take the picture.

4.2 The JavaScript

;(function(){
    function userMedia(){
        return navigator.getUserMedia = navigator.getUserMedia ||
        navigator.webkitGetUserMedia ||
        navigator.mozGetUserMedia ||
        navigator.msGetUserMedia || null;

    }

    // Now we can use it
    if( userMedia() ){
        var videoPlaying = false;
        var constraints = {
            video: true,
            audio:false
        };
        var video = document.getElementById('v');

        var media = navigator.getUserMedia(constraints, function(stream){

            // URL Object is different in WebKit
            var url = window.URL || window.webkitURL;

            // create the url and set the source of the video element
            video.src = url ? url.createObjectURL(stream) : stream;

            // Start the video
            video.play();
            videoPlaying  = true;
        }, function(error){
            console.log("ERROR");
            console.log(error);
        });

        // Listen for user click on the "take a photo" button
        document.getElementById('take').addEventListener('click', function(){
            if (videoPlaying){
                var canvas = document.getElementById('canvas');
                canvas.width = video.videoWidth;
                canvas.height = video.videoHeight;
                canvas.getContext('2d').drawImage(video, 0, 0);
                var data = canvas.toDataURL('image/webp');
                document.getElementById('photo').setAttribute('src', data);
            }
        }, false);

    } else {
        console.log("KO");
    }
})();

As you can see I’ve only added a variable for capturing the video status (if it’s playing or not) var videoPlaying = false;.

Then for taking the photo I added an event Listener on the button click ::

document.getElementById('take').addEventListener('click', function(){ /*...*/});

When the user click on the button, if the video is playing, we, create draw the Video image in the canvas (even if the canvas is not visible) :

canvas.getContext('2d').drawImage(video, 0, 0);

Next, we create a data URL for define the image src attribute.

var data = canvas.toDataURL('image/webp');
document.getElementById('photo').setAttribute('src', data);

5. Download

Download
You can download the full source code of this example here: HTML5 Webcam Example

Remi Goyard

I'm a senior web architect. Passionated by new technologies, programming, devops tools, and agile methodologies. I really enjoy to coach, or teach, people who wants to learn programming, from beginners to skilled programmers. Involved in local developer communities, Java User Group, PHP User Group, or Javascript User Group, i like to share with others about experiences, news or business. Coding is FUN !
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

8 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
aarthi
aarthi
9 years ago

Hi,
I’m building a mobile app using phonegap. The above code is not working for me. I am using Micromax tab. I have tried on the mobile browser, chrome and opera browsers in my tab.

The mobile has two buttons, 1, take a selfie 2 Upload Image. Your code should work pretty good for this.

Can u tell me what could be wrong?

Thanks in advance..

Raghuvir
Raghuvir
8 years ago
Reply to  aarthi

Hi , I am trying to do the same .
Did you find any solution ??

I am creating one Cordova ionic app, when app runs in mobile devices it should access camera of mobile device , and when I run the same app in desktop browser , it should access my desktop camera.

please do let me if there is any solution.

Thanks for help.

Paul
Paul
9 years ago

Hello,
This code help me a lot.
i want to ask you that , how can we access two usb cameras on same web page using these getmediauser. I can access one camera
Any help will be appreciated
Thanks.

Ishan
Ishan
8 years ago

Thank you, Remi, for sharing this example. This code helped me a lot.

john
john
8 years ago

i have tried to get this working on every browser i have and the only one i seen to get it working on is edge ironically enough

prasad
prasad
8 years ago

great sir…thax a lots………..these code is help me lots of in my programming……..personally thax for …….

Oleg
Oleg
7 years ago

…lease full html-code this examp…

chris
chris
7 years ago

Great intro. This has been deprecated. Any chance you’ll be doing an updated version using navigator.mediaDevices.getUserMedia() ?

Back to top button