html5调用电脑摄像头

来源:互联网 发布:大学用的java教材 编辑:程序博客网 时间:2024/02/24 05:22

       以前我们需要使用第三方的插件才能从浏览器里访问用户的摄像头,这不免有些复杂。现在只需要HTML5的画布技术和javaScript,我们就能简单快速的操作用户的摄像头。不仅仅还是访问摄像头,而且是因为HTML5的画布技术及其强大,我们可以给图片上加入各种迷人的滤镜效果。现在,在浏览器里用自己的摄像头给自己拍张照片吧!

代码如下:

<!DOCTYPE html><html><head></head><body><video id="video" width="640" height="480" autoplay></video><button id="snap">Snap Photo</button><canvas id="canvas" width="640" height="480"></canvas></body></html><script type="text/javascript">// Put event listeners into placewindow.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 placeif(navigator.getUserMedia) { // Standardnavigator.getUserMedia(videoObj, function(stream) {video.src = stream;video.play();}, errBack);} else if(navigator.webkitGetUserMedia) { // WebKit-prefixednavigator.webkitGetUserMedia(videoObj, function(stream){video.src = window.webkitURL.createObjectURL(stream);video.play();}, errBack);}else if(navigator.mozGetUserMedia) { // Firefox-prefixednavigator.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);</script>

注:必须要把html文件部署到服务器上才能调用摄像头,在本地无法直接打开调用。

0 0
原创粉丝点击