Webcam in HTML5
In the previous blog post, I have glanced at HTML5. Probably many people have already experienced some cool functions of HTML5. In this article, I would like to share how to invoke Webcam in HTML5.
While strolling through StackOverflow, I found there are many questions about how to display webcam in a web browser. Using HTML5, with a few tricks, can manage to show a Webcam in a web browser conveniently.
Please follow this tutorial step by step, and you can instantly build a webcam application in a web browser.
Create a Video Element and Two Button Elements
<video id="video"></video>
<button id="start">start</button>
<button id="stop">stop</button>
Initialize
var streaming = false,
video = document.querySelector('#video'),
start = document.querySelector('#start'),
stop = document.querySelector('#stop'),
width = 320,
height = 0;
Get video
navigator.getMedia = (navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia);
navigator.getMedia(
{
video: true,
audio: false
},
function (stream) {
if (navigator.mozGetUserMedia) {
video.mozSrcObject = stream;
} else {
var vendorURL = window.URL || window.webkitURL;
video.src = vendorURL.createObjectURL(stream);
}
video.play();
},
function (err) {
console.log("An error occured! " + err);
}
);
Resize video
video.addEventListener('canplay', function (ev) {
if (!streaming) {
height = video.videoHeight / (video.videoWidth / width);
video.setAttribute('width', width);
video.setAttribute('height', height);
canvas.setAttribute('width', width);
canvas.setAttribute('height', height);
streaming = true;
}
}, false);
Start or stop video
start.addEventListener('click', function (ev) {
video.play();
ev.preventDefault();
}, false);
stop.addEventListener('click', function (ev) {
video.pause();
ev.preventDefault();
}, false);
Pretty easy. For further reading, you can refer to Mozilla’s WebRTC docs.
HTML5 is definitely the trend of web technology. However, it is not so mature yet. Browsers are adopting features from HTML5 and evolving themselves over time. In the current stage, considering the compatibility and the security, using a 3rd-party webcam plugin, like ImageCapture Suite, would be a good option, especially if your image capture project has a tight schedule. Besides image acquisition, the plugin also allows you to do simple image processing, HTTP uploading and downloading. ImageCapture Suite supports all the mainstream web browsers like Chrome, IE, Firefox, and Opera on both Mac and Windows platform.