The recently released version of Chrome (version 21) has officially added webcam and microphone support through the availability of a new JavaScript method called getUserMedia(). The idea is that your JavaScript code requests access to a user’s webcam and/or microphone. Google Chrome will prompt the user with a dialog bar at the top of the window notifying the user what the browser is requesting. The user has the option of accepting or rejecting this request so your web application should handle this gracefully. The dialog bar also offers an “Options” menu that lets the user pick which camera or microphone to use before accepting the request.

The best way to see this in practice is with a live example, so if you’re using the latest version of Google Chrome and have a webcam, you should see a prompt at the top of the window asking for access to your camera. If you allow it, you should see the live feed from your webcam immediately below here.

The code that makes all of this happen involves a <video> element (with autoplay; this is important) and some JavaScript. The following code is what makes the above possible.

<div id="container" style="text-align: center;"><video id="webcam" width="400" height="300" autoplay><span style="font-weight: bold;">Your browser does not support the &lt;video&gt; element.</span></video></div>
<script type="text/javascript">
    if (typeof navigator.webkitGetUserMedia == 'function') {
        navigator.webkitGetUserMedia({video: true, audio: false}, 
            function(stream) {
                // Successfully connected to the webcam
                document.getElementById('webcam').src = webkitURL.createObjectURL(stream);
            },
            function(error) {
                // User denied or an error occurred
                document.getElementById('container').innerHTML = '<span style="font-weight: bold;">User denied camera acccess or there was a problem retrieving a stream from the camera. Reload this page to try again.</span>';
            }
        );
    }
</script>

Since you are using the HTML5 <video> element to display the webcam stream, there are all sorts of cool things you can accomplish using CSS3 filter effects and some additional JavaScript. I will update this post with some more examples as I continue to play around with the possibilities!