參考HTML5Rocks實現的一個簡單的例子。 來源網址:https://segmentfault.com/a/1190000000354671css
思路以下:
1. 把冰箱門打開
2. 把大象放進冰箱裏
3. 把冰箱門關上html
好了不開玩笑了,其實思路是:
1. 經過getUserMedia調用設備的攝像頭(電腦、手機均可以,取決於瀏覽器對這個API的支持狀況),並將資源放入video標籤。
2. 將video內的視頻資源經過canvas的drawImage API放入canvas裏,這個canvas是不顯示的。
3. 將canvas的內容轉換成base64編碼的webp格式的圖像(若是瀏覽器不支持這個格式,會fallback到png格式)放入img裏,因而你就能看到你拍的照片了。html5
上代碼:web
/**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>
JScanvas
1 var video = document.querySelector('video'); 2 var canvas = document.querySelector('canvas'); 3 var ctx = canvas.getContext('2d'); 4 var localMediaStream = null; 5 6 var snapshot = function () { 7 if (localMediaStream) { 8 ctx.drawImage(video, 0, 0); 9 document.querySelector('img').src = canvas.toDataURL('image/webp'); 10 } 11 }; 12 13 var sizeCanvas = function () { 14 setTimeout(function () { 15 canvas.width = video.videoWidth; 16 canvas.height = video.videoHeight; 17 img.width = video.videoWidth; 18 img.height = video.videoHeight; 19 }, 100); 20 }; 21 22 var btnCapture = document.getElementById('capture'); 23 btnCapture.addEventListener('click', snapshot, false); 24 25 navigator.webkitGetUserMedia( 26 {video: true}, 27 function (stream) { 28 video.src = window.URL.createObjectURL(stream); 29 localMediaStream = stream; 30 sizeCanvas(); 31 }, 32 function () { 33 alert('your browser does not support getUserMedia'); 34 } 35 );
1 // cross platforms 2 var myGetUserMedia = navigator.getUserMedia || 3 navigator.webkitGetUserMedia || 4 navigator.mozGetUserMedia || 5 navigator.msGetUserMedia;