HTML5 – How to access and take picture using Camera API

HTML5 – How to access and take picture using Camera API

HTML5 has introduced some great features and APIs.  One of the APIs is  getUserMedia API. This API provide access to the Camera. To make this API work we have to do simple JavaScript with HTML5.

Here is a simple HTML5 code structure that you can use.

This code structure defines a video element and a button to take picture, that would be placed the picture inside a canvas element.

Below is the JavaScript code for accessing the camera and taking a picture. I will explain it later below.


After load of document, we get canvas element from HTML and then 2d context and video element.

After that we check that whether user’s browser supports the getUserMedia  API using standard, webkit and Firefox prefixes.

Once the getUserMedia  API is initialized


method sets the video element’s src to the user’s live camera/webcam.

To  take picture from the live video we need to add code for the click event of  “Take Picture” button as under.

The cod above will draw an image on canvas from live video.

Below is the complete working code for accessing Camera and taking a picture with some simple CSS.

Save the code below in a file named “index.html” form example and then run ina modern browser like Firefox or Chrome and see the magic of HTML5 getUserMedia  API .

In next tutorial we will discuss more advanced features of  HTML5. Stay tuned.

Zip code file to download

Note:  inspired this article from David Walsh.