Have you created a web application and want to use the client's webcam to do some awesome stuff, such as creating a video stream for video conferencing, clicking a photo etc? Then this post is for you!
NOTE: You need an https server in order to make it work. Also, accessing the webcam in this way is secure, as the user will be prompted before it is switched on.
There is an existing library written in Javascript called Webcam.js that allows you to use the webcam in a webpage. You can download the javascript file from this github repository:
https://github.com/jhuckaby/webcamjs
After downloading, place the file in your project directory. For the purpose of this tutorial, let'ss create a new folder named webcamJS inside /var/www/html/. Paste this snippet inside a file named index.html:
<html> <head> <title>Tutorial</title> <script src="webcam.js"></script> </head> <body> <div id="my_camera" style="width:320px;height:240px;"></div> <!-- An empty div where live stream from the webcam will be shown --> <div id="my_result" style="width:320px;height:240px;"></div> <!-- An empty div where the clicked photo will be shown --> <button type="button" class="button" onClick="take_snapshot()">Click</button> <!-- Click an image and show it in my_result div --> </body> <script> Webcam.attach('#my_camera') function take_snapshot(){ Webcam.snap( function(data_uri) { document.getElementById('my_result').innerHTML = '<img src="'+data_uri+'"/>'; }); } </script> </html>
That's it! Run the file by typing the following in your browser:
127.0.0.1/webcamJS/index.html.
Here is a sample screenshot of the webpage after clicking a photo:
You can do even more useful stuff using this library. Just refer to the official docs here.
No comments:
Post a Comment