

不废话了,上代码:
HTML
<!doctype html> <html> <head> <title>html5 capture test</title> <link rel="stylesheet" href="style.css"> </head> <body> <video autoplay></video> <img src=""> <canvas style="display: none;"></canvas> <button id="capture">snapshot</button> <script src="index.js"></script> </body> </html>
JS
var video = document.querySelector('video');
var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');
var localMediaStream = null;
var snapshot = function () {
 if (localMediaStream) {
 ctx.drawImage(video, 0, 0);
 document.querySelector('img').src = canvas.toDataURL('image/webp');
 }
};
var sizeCanvas = function () {
 setTimeout(function () {
 canvas.width = video.videoWidth;
 canvas.height = video.videoHeight;
 img.width = video.videoWidth;
 img.height = video.videoHeight;
 }, 100);
};
var btnCapture = document.getElementById('capture');
btnCapture.addEventListener('click', snapshot, false);
navigator.webkitGetUserMedia(
 {video: true},
 function (stream) {
 video.src = window.URL.createObjectURL(stream);
 localMediaStream = stream;
 sizeCanvas();
 },
 function () {
 alert('your browser does not support getUserMedia');
 }
);几个注意事项:
不同浏览器对getUserMedia的支持情况不同,需要加上前缀,比如webkitGetUserMedia、mozGetUserMedia、msGetUserMedia,如果你想屏蔽这一问题的话,可以这样做:
// cross platforms var myGetUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
Chrome对file:///做了很多的限制,跨域就不说了,geolocation也不能在本地下使用,这个getUserMedia也是。
这个sizeCanvas函数做的事情就是保证你拍到的照片的大小和摄像头拍到的大小是一样的,否则会出现拍到的照片只有摄像头录到的一部分画面的情况。
