使用 HTML 实现拍照功能需要结合 JavaScript 和浏览器提供的 WebRTC(Web 实时通信)技术。以下是大致步骤:
<video id="video" autoplay></video>
<button id="snap">Take Photo</button>
const video = document.getElementById('video');
navigator.mediaDevices.getUserMedia({ video: true, audio: false })
.then(stream => {
video.srcObject = stream;
})
.catch(err => {
console.error('Error accessing camera', err);
});
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
document.getElementById('snap').addEventListener('click', () => {
context.drawImage(video, 0, 0, canvas.width, canvas.height);
});
const dataURL = canvas.toDataURL('image/jpeg');
document.getElementById('photo').setAttribute('src', dataURL);
需要注意的是,拍照功能仅在支持 WebRTC 技术的现代浏览器中可用,例如 Google Chrome、Firefox 和 Safari。