[HTML] 纯文本查看 复制代码 <!DOCTYPE html>
<html>
<head>
<title>调用摄像头实时显示和抓拍示例</title>
<style>
#video {
width: 50%;
height: auto;
}
</style>
</head>
<body>
<video id="video" autoplay></video>
<button id="open-button">打开摄像头</button>
<button id="close-button">关闭摄像头</button>
<button id="capture-button">拍照</button>
<canvas id="canvas" style="display: none;"></canvas>
<script>
// 获取元素
const video = document.getElementById('video');
const openButton = document.getElementById('open-button');
const closeButton = document.getElementById('close-button');
const captureButton = document.getElementById('capture-button');
const canvas = document.getElementById('canvas');
let stream;
// 打开摄像头
function openCamera() {
const constraints = {
video: {
facingMode: 'environment',
width: { ideal: 1280 },
height: { ideal: 720 }
}
};
navigator.mediaDevices.getUserMedia(constraints)
.then(function (mediaStream) {
stream = mediaStream;
video.srcObject = stream;
})
.catch(function (error) {
console.error('摄像头打开失败:', error);
});
}
// 关闭摄像头
function closeCamera() {
if (stream) {
const tracks = stream.getTracks();
tracks.forEach(function (track) {
track.stop();
});
video.srcObject = null;
}
}
// 拍照按钮点击事件
captureButton.addEventListener('click', function() {
// 设置画布尺寸与视频分辨率一致
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
// 将视频帧绘制到画布上
canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
// 将画布内容转为图像数据 URL
const imageUrl = canvas.toDataURL('image/png');
// 创建一个链接并设置图像数据 URL 为链接地址
const link = document.createElement('a');
link.href = imageUrl;
link.download = 'photo.png'; // 下载图片的文件名
// 模拟点击链接,触发下载
link.click();
});
// 打开摄像头按钮点击事件
openButton.addEventListener('click', function() {
openCamera();
});
// 关闭摄像头按钮点击事件
closeButton.addEventListener('click', function() {
closeCamera();
});
</script>
</body>
</html>
|