<div id="camera"></div>
然后在JavaScript中用getUserMedia()函數(shù)請(qǐng)求授權(quán),獲取攝像頭:<script>
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
if (navigator.getUserMedia) {
navigator.getUserMedia({video: true}, handleVideo, videoError);
}
function handleVideo(stream) {
var video = document.getElementById('camera');
video.srcObject = stream;
}
function videoError(e) {
//錯(cuò)誤代碼
}
</script>
接下來是拍照和上傳的代碼,用Canvas將攝像頭拍攝的圖片轉(zhuǎn)換成Base64編碼,并發(fā)送給服務(wù)器:<canvas id="canvas" style="display:none"></canvas>
<button id="takePhoto">拍照</button>
<script>
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var video = document.getElementById('camera');
var takePhoto = document.getElementById('takePhoto');
takePhoto.addEventListener('click', function() {
context.drawImage(video, 0, 0, canvas.width, canvas.height);
var dataURL = canvas.toDataURL('image/png');
//將dataURL發(fā)送給服務(wù)器
});
</script>
以上就是HTML5手機(jī)拍照效果的代碼,可以讓我們?cè)诰W(wǎng)頁上實(shí)現(xiàn)拍照并上傳照片。但是由于getUserMedia在不同瀏覽器中的兼容性問題,需要做好瀏覽器兼容性處理,以保證在不同設(shè)備和瀏覽器上都能正常使用。