Welcome folks today in this blog post we will be capturing an image from webcam using the webrtc api in javascript using html5 and css3. All the source code of the example is shown below
Get Started
In order to get started you need to create a index.html
file and write the actual html code as shown below
index.html
1 2 3 4 5 |
<div class="button-group"> <button id="btn-start" type="button" class="button">Start Streaming</button> <button id="btn-stop" type="button" class="button">Stop Streaming</button> <button id="btn-capture" type="button" class="button">Capture Image</button> </div> |
In this block of code we have three html5
buttons first one is for start the camera and second is for stopping the camera and the third button is for capturing the image from the webcam.
1 2 3 4 5 6 7 8 9 10 11 12 |
<!-- Video Element & Canvas --> <div class="play-area"> <div class="play-area-sub"> <h3>The Stream</h3> <video id="stream" width="320" height="240"></video> </div> <div class="play-area-sub"> <h3>The Capture</h3> <canvas id="capture" width="320" height="240"></canvas> <div id="snapshot"></div> </div> </div> |
And now in the block of code we have the actual layout and the area where we will be rendering the actual live camera feed stream and the area where the captured image will be shown to the user. This is side by side layout using some custom css that we will write in the next step.
And now we need to apply some custom css to this html5 layout. The custom css is shown below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
.button-group, .play-area { border: 1px solid grey; padding: 1em 1%; margin-bottom: 1em; } .button { padding: 0.5em; margin-right: 1em; } .play-area-sub { width: 47%; padding: 1em 1%; display: inline-block; text-align: center; } #capture { display: none; } #snapshot { display: inline-block; width: 320px; height: 240px; } |
And now if you open the index.html inside the browser the layout will look something like this as shown below
And now we will write the javascript code to actually build the logic of the app.
1 2 3 4 5 6 7 8 9 10 11 12 |
// The buttons to start & stop stream and to capture the image var btnStart = document.getElementById( "btn-start" ); var btnStop = document.getElementById( "btn-stop" ); var btnCapture = document.getElementById( "btn-capture" ); // The stream & capture var stream = document.getElementById( "stream" ); var capture = document.getElementById( "capture" ); var snapshot = document.getElementById( "snapshot" ); // The video stream var cameraStream = null; |
Here in this first step we are getting all the references of the DOM Elements by using the class names and ID’s which are given to them. And also we are initializing a cameraStream variable and we have given value null to it.
Attaching the Event Listeners to all the Buttons
1 2 3 4 |
// Attach listeners btnStart.addEventListener( "click", startStreaming ); btnStop.addEventListener( "click", stopStreaming ); btnCapture.addEventListener( "click", captureSnapshot ); |
Here in this block of code we are attaching the event listeners to all the three buttons. All the three functions we will write in the next steps.
Start the Camera
Now in this javascript code we will start the camera and display the live stream
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
// Start Streaming function startStreaming() { var mediaSupport = 'mediaDevices' in navigator; if( mediaSupport && null == cameraStream ) { navigator.mediaDevices.getUserMedia( { video: true } ) .then( function( mediaStream ) { cameraStream = mediaStream; stream.srcObject = mediaStream; stream.play(); }) .catch( function( err ) { console.log( "Unable to access camera: " + err ); }); } else { alert( 'Your browser does not support media devices.' ); return; } } |
So basically we are writing the startStreaming() function which basically use the navigator api to grant the access of the webcam which is available inside your browser. After the user grants the access the camera stream is returned in the callback function. That camera live stream we are displaying in the html. And then we are using the play()
method to actually play the camera stream.
So now if you open the html5 file inside the browser the camera stream will be showing as shown below
Stop the Camera Stream
Here in this step guys we will look how to stop the camera when the user press the stop button inside the app
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// Stop Streaming function stopStreaming() { if( null != cameraStream ) { var track = cameraStream.getTracks()[ 0 ]; track.stop(); stream.load(); cameraStream = null; } } |
So here in this stop function we are first of all checking if the cameraStream variable is not null means if the camera is running then we are getting the track of the live stream using getTracks() method and then we are getting the first element inside the array. And then we are calling the stop() method on the track object to actually stop the live stream. And lastly we are also setting the cameraStream variable to null.
Capturing Image From Webcam
Lastly we will be capturing the image from the webcam. We will writing the function required for this as shown below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
function captureSnapshot() { if( null != cameraStream ) { var ctx = capture.getContext( '2d' ); var img = new Image(); ctx.drawImage( stream, 0, 0, capture.width, capture.height ); img.src = capture.toDataURL( "image/png" ); img.width = 240; snapshot.innerHTML = ''; snapshot.appendChild( img ); } } |
Here we are using the getContext() method to get the 2d
context of the camera object. And then we are initializing a new Image() and drawing the image providing the camera stream as an argument and also providing the x and y coordinates and also providing the width and height of the captured image. And also guys we are getting the url of the image using the toDataURL() method and setting the src attribute of the newly created image and we are setting the width of the image to be 240. And also lastly we are appending the image to the DOM.
Full Example Source Code
Now we will be sharing the full example source code of this application
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
// The buttons to start & stop stream and to capture the image var btnStart = document.getElementById( "btn-start" ); var btnStop = document.getElementById( "btn-stop" ); var btnCapture = document.getElementById( "btn-capture" ); // The stream & capture var stream = document.getElementById( "stream" ); var capture = document.getElementById( "capture" ); var snapshot = document.getElementById( "snapshot" ); // The video stream var cameraStream = null; // Attach listeners btnStart.addEventListener( "click", startStreaming ); btnStop.addEventListener( "click", stopStreaming ); btnCapture.addEventListener( "click", captureSnapshot ); // Start Streaming function startStreaming() { var mediaSupport = 'mediaDevices' in navigator; if( mediaSupport && null == cameraStream ) { navigator.mediaDevices.getUserMedia( { video: true } ) .then( function( mediaStream ) { cameraStream = mediaStream; stream.srcObject = mediaStream; stream.play(); }) .catch( function( err ) { console.log( "Unable to access camera: " + err ); }); } else { alert( 'Your browser does not support media devices.' ); return; } } // Stop Streaming function stopStreaming() { if( null != cameraStream ) { var track = cameraStream.getTracks()[ 0 ]; track.stop(); stream.load(); cameraStream = null; } } function captureSnapshot() { if( null != cameraStream ) { var ctx = capture.getContext( '2d' ); var img = new Image(); ctx.drawImage( stream, 0, 0, capture.width, capture.height ); img.src = capture.toDataURL( "image/png" ); img.width = 240; snapshot.innerHTML = ''; snapshot.appendChild( img ); } } |