Webcam to canvas or data URI with HTML5 and Javascript

This post has been sitting around unfinished since April so I thought I should finish it and get it out there.

In this post I am going to show how you can capture an image from a webcam via JavaScript and convert it to a Data URI which can then be saved in a database or displayed in an IMG tag.

Note: This is more of a proof of concept rather than a best practices example so the code is a bit messy and hacked together from various sources.

I have only tested this on Safari for iOS 6 and latest Chrome with a webcam. It may or may no work in other browsers.

View demo

All explanations for the the code and markup are in the code comments, so please read them for more detail.

Here is a basic HTML page with some simple CSS for this demonstration:
[cc lang=”html”]




Display Webcam Stream



[/cc]

In the body we add the following elements:

[cc lang=”html”]

<-- Selected image will be draw to a canvas -->


<-- Or alternatively added to an img tag -->
capture

<-- For the JavaScript below -->

[/cc]

Finally we’ll add the following Javascript to the script tag inside the body:

[cc lang=”javascript”]
var video = document.querySelector(“#videoElement”);

// check for getUserMedia support
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia || navigator.oGetUserMedia;

if (navigator.getUserMedia) {
// get webcam feed if available
navigator.getUserMedia({video: true}, handleVideo, videoError);
}

function handleVideo(stream) {
// if found attach feed to video element
video.src = window.URL.createObjectURL(stream);
}

function videoError(e) {
// no webcam found – do something
}
var v,canvas,context,w,h;
var imgtag = document.getElementById(‘imgtag’); // get reference to img tag
var sel = document.getElementById(‘fileselect’); // get reference to file select input element

document.addEventListener(‘DOMContentLoaded’, function(){
// when DOM loaded, get canvas 2D context and store width and height of element
v = document.getElementById(‘videoElement’);
canvas = document.getElementById(‘canvas’);
context = canvas.getContext(‘2d’);
w = canvas.width;
h = canvas.height;

},false);

function draw(v,c,w,h) {

if(v.paused || v.ended) return false; // if no video, exit here

context.drawImage(v,0,0,w,h); // draw video feed to canvas

var uri = canvas.toDataURL(“image/png”); // convert canvas to data URI

// console.log(uri); // uncomment line to log URI for testing

imgtag.src = uri; // add URI to IMG tag src
}

document.getElementById(‘save’).addEventListener(‘click’,function(e){

draw(v,context,w,h); // when save button is clicked, draw video feed to canvas

});

// for iOS

// create file reader
var fr;

sel.addEventListener(‘change’,function(e){
var f = sel.files[0]; // get selected file (camera capture)

fr = new FileReader();
fr.onload = receivedData; // add onload event

fr.readAsDataURL(f); // get captured image as data URI
})

function receivedData() {
// readAsDataURL is finished – add URI to IMG tag src
imgtag.src = fr.result;
}
[/cc]

That is all the code that’s required. The new HTML5 APIs make it very quick and easy to do some interesting stuff!

View demo


Comments

19 responses to “Webcam to canvas or data URI with HTML5 and Javascript”

  1. mesmerico Avatar
    mesmerico

    Excellent, It works perfect. I’ll try to save the image in a BD and tell you how it goes.

  2. Demo doesn’t work iOS 7 iPhone 5

    1. benfoster4130 Avatar
      benfoster4130

      iOS doesn’t allow direct access to the webcam via the browser so you have to use the file browser and take a photo from there. I don’t have an iPhone so I can’t test on that but it works on iOS 7 on iPad 2

    2. Because iPhone sux ;_;

  3. how can i save the file in my local folder?

  4. Its work perfectly in Chrome browser

  5. worked great on my iphone5s with ios7, but the image was very narrow. i read somewhere there s a ios safari bug causing this..

  6. Erwinus Avatar
    Erwinus

    Works in latest firefox and chrome! Does not work in IE at all. Does not work in Opera. Windows 7.

  7. Excellent, it working.

  8. Altuğ Gürkaynak Avatar
    Altuğ Gürkaynak

    Works like a mirracle but I couldn’t find a way to save my image to server 🙁 Can you help me?

    1. Altuğ Gürkaynak Avatar
      Altuğ Gürkaynak

      and I need to send it to server in base64 form also

  9. Don Zanurano Avatar
    Don Zanurano

    its doesnt work in iphone 5 ios 7

  10. Manikandan Rangan Avatar
    Manikandan Rangan

    This demo not working in chrome browser for past 1 week, any idea for this issue

    1. Chrome has since blocked webcam access to any pages that aren’t served via HTTPS.

      1. Manikandan Rangan Avatar
        Manikandan Rangan

        Hi Ben Foster,
        Thanks for your reply!!!

        Any another possible way to overcome this issue, bcoz of recently i used this js for 2 project thats why i am asking

        Thanks
        Manikandan Rangan

        1. just setup SSL, startssl.com gives out free certificates and it’s super easy to setup.

  11. Muhammed Shuhaib Avatar
    Muhammed Shuhaib

    It is not a mirror type.. How to invert canvas ??

Leave a Reply