On today’s tutorial I’ll teach how to take snapshots from webcam using only HTML5.
On the past, accessing user webcam was something onerous, sometimes falling back on Flash. Gladly, HTML5 brought an innovation to this area, thanks to the <video> tag.
Getting webcam access
On our demo we’re going to create a tag to display the live stream of webcam, a tag to display a webcam snapshot, and two buttons: One to take a snapshot and another to save (download) the photo.
<videoid="video"width="640"height="480"autoplay></video><!-- Live stream of webcam --><canvasid="canvas"width="640"height="480"></canvas><!-- Snapshot of webcam --><buttonid="snap">Take snapshot</button><!-- Button to take snapshot --><aid="save"download><button>Download photo</button></a><!-- Button to download photo -->
There are three ways to get access to the user webcam, depending on his browser: getUserMedia (for IE and alike), webkitGetUserMedia (for Chrome and Safari) and mozGetUserMedia (for Firefox), so we need to handle all them.
Inside the listener there are three “if”, for compatibility reasons described above.
Each “if” is similar, just some changes here and there: We are setting “video.src” to webcam stream (remember: video variable is the <video> tag we set previously) and immediately playing it through the function “play()”. We also need to pass a callback function in case of error (permission not given or webcam not found, for example).
Taking a snapshot
Now we’re going to implement the take snapshot functionality. First thing: Create a listener to when button “Take snapshot” is clicked:
This listener must be inside “DOMContentLoaded” listener created previously.
Now, inside this new listener that we’ve created, let’s draw a webcam frame inside the <canvas> tag that we created on first section of this tutorial. To be able to draw an image inside a canvas, we first need to get its “context” and through it call the function “drawImage(x, y, width, height)”, where x, y representates the origin of source image (if you need to translate it…) and width, height the area you are going to take from source image (if you need to crop it…).