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
