html5中一个有趣的 API,能够调用电脑的摄像头,结合 <video> 标签和 Canvas 就能在浏览器中拍摄照片了。
这里需要注意:
因为安全问题, chrome 对于本地文件禁用了很多功能(以file:///开头). 所以如果你直接把html文件拖进chrome是看不到效果的(getUserMedia 失败). 这个问题让我疑惑了挺久的.
解决办法:
1. 使用IDE 来查看效果, 比如webstorm.
2. 配合http服务器. 比如python simplehttpserver. 或者apache等等.
3. 关闭所有chrome窗口(否则参数无效). 在命令行中增加如下参数启动chrome.
chrome --allow-file-access-from-files
一个示例
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> <p>Using Opera Next or Chrome Canary, use this page to take your picture!</p> <video id="video" width="640" height="480" autoplay></video> <button id="snap" class="sexyButton">Snap Photo</button> <canvas id="canvas" width="640" height="480"></canvas> <script> // 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) { // WebKit-prefixed navigator.mozGetUserMedia(videoObj, function(stream){ video.src = window.URL.createObjectURL(stream); video.play(); }, errBack); } // Trigger photo take document.getElementById("snap").addEventListener("click", function() { context.drawImage(video, 0, 0, 640, 480); }); }, false); </script> </body> </html>
代码参考自 http://davidwalsh.name/demo/camera.php
时间: 2024-10-12 09:57:16