以前我们需要使用第三方的插件才能从浏览器里访问用户的摄像头,这不免有些复杂。现在只需要HTML5的画布技术和javaScript,我们就能简单快速的操作用户的摄像头。不仅仅还是访问摄像头,而且是因为HTML5的画布技术及其强大,我们可以给图片上加入各种迷人的滤镜效果。现在,在浏览器里用自己的摄像头给自己拍张照片吧!
代码如下:
Snap Photo
// Put event listeners into place
window.addEventListener("DOMContentLoaded", function() {
// Grab elements, create settings, etc.
var canvas = document.getElementById("canvas"),
context = canvas.getContext("2d"),
video = document.getElementById("video"),
videoObj = { "video": true },
errBack = function(error) {
console.log("Video capture error: ", error.code);
};
// Put video listeners into place
if(navigator.getUserMedia) { // Standard
navigator.getUserMedia(videoObj, function(stream) {
video.src = stream;
video.play();
}, errBack);
} else if(navigator.webkitGetUserMedia) { // WebKit-prefixed
navigator.webkitGetUserMedia(videoObj, function(stream){
video.src = window.webkitURL.createObjectURL(stream);
video.play();
}, errBack);
}
else if(navigator.mozGetUserMedia) { // Firefox-prefixed
navigator.mozGetUserMedia(videoObj, function(stream){
video.src = window.URL.createObjectURL(stream);
video.play();
}, errBack);
}
// 触发拍照动作
document.getElementById("snap")
.addEventListener("click", function() {
context.drawImage(video, 0, 0, 640, 480);
});
}, false);
注:必须要把html文件部署到服务器上才能调用摄像头,在本地无法直接打开调用。