Monthly Archives: August 2012

Simple HTML5 Webcam Example

Here’s a quick example that shows you how to access your web camera with HTML5 and JavaScript. (Works in Chrome 21).

<video autoplay id="vid" style="display:none;"></video>
<canvas id="canvas" width="640" height="480" style="border:1px solid #d3d3d3;"></canvas><br>
<button onclick="snapshot()">Take Picture</button>

<script type="text/javascript">

    var video = document.querySelector("#vid");
    var canvas = document.querySelector('#canvas');
    var ctx = canvas.getContext('2d');
    var localMediaStream = null;

    var onCameraFail = function (e) {
        console.log('Camera did not work.', e);

    function snapshot() {
        if (localMediaStream) {
            ctx.drawImage(video, 0, 0);

    navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
    window.URL = window.URL || window.webkitURL;
    navigator.getUserMedia({video:true}, function (stream) {
        video.src = window.URL.createObjectURL(stream);
        localMediaStream = stream;
    }, onCameraFail);


Just cut and paste the code above into your browser and you should be good to go. Also to view the video just set style of the video tag to inline or block.