先看效果:
帅哥美女可以先点赞收藏哈!!
话不多说,直接上代码:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>摄像头拍照</title>
<style>
#videoElement {
width: 100%;
max-width: 600px;
height: auto;
}
#canvasElement {
display: none;
}
#captureButton {
margin-top: 10px;
padding: 10px 20px;
background-color: #007bff;
color: #fff;
border: none;
cursor: pointer;
}
</style>
</head>
<body>
<video id="videoElement" autoplay></video>
<button id="captureButton">拍照</button>
<canvas id="canvasElement"></canvas>
<img id="photo" style="display: none;" />
<script>
const video = document.getElementById('videoElement');
const canvas = document.getElementById('canvasElement');
const captureButton = document.getElementById('captureButton');
const photo = document.getElementById('photo');
const constraints = {
video: true
};
// 初始化摄像头
async function initCamera() {
try {
const stream = await navigator.mediaDevices.getUserMedia(constraints);
handleSuccess(stream);
} catch (e) {
console.error('访问摄像头出错: ', e);
}
}
// 显示摄像头视频流
function handleSuccess(stream) {
video.srcObject = stream;
}
// 捕获视频流中的图像
function captureImage() {
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
const dataURL = canvas.toDataURL('image/png');
// 显示拍摄的照片
photo.src = dataURL;
photo.style.display = 'block';
}
// 页面加载时初始化摄像头
window.onload = () => {
initCamera();
};
// 拍照按钮点击事件
captureButton.addEventListener('click', captureImage);
</script>
</body>
</html>