<template>
<n-card style="width: 660px" title="请对准摄像头" :bordered="false" size="huge" role="dialog" aria-modal="true">
<div flex>
<div text-center class="text-[#8dc6e5]">
<div mb2>摄像头实时画面</div>
<div w40 h50>
<dv-border-box-8 p10px>
<video ref="video" autoplay wh-full></video>
</dv-border-box-8>
</div>
</div>
<div ml15 mr15 mt15>
<n-button type="tertiary" w20 @click="takePhoto">
拍照
</n-button>
<n-button type="info" mt2 w20 @click="submitData">
保存
</n-button>
</div>
<div text-center class="text-[#8dc6e5]">
<div mb2>拍照图片</div>
<div w40 h50>
<dv-border-box-8 p10px>
<img ref="photo" style="display: none" wh-full>
</dv-border-box-8>
</div>
</div>
</div>
</n-card>
</template>
<script setup>
import { onMounted } from "vue"
const video = ref(null)
const photo = ref(null)
const takePhoto = () => {
// 创建一个canvas
const canvas = document.createElement('canvas');
canvas.width = video.value.videoWidth;
canvas.height = video.value.videoHeight;
// 将摄像头捕捉到的图像绘制到canvas上
canvas.getContext('2d').drawImage(video.value, 0, 0, canvas.width, canvas.height);
// 将canvas转换为图片
photo.value.src = canvas.toDataURL('image/png');
// 显示图片
photo.value.style.display = 'block';
}
const clearVideo = () => {
// 关闭摄像头
const stream = video.value.srcObject;
const tracks = stream.getTracks();
tracks.forEach(track => {
track.stop();
});
video.value.srcObject = null;
}
const submitData = () => {
// 提交成功后清空
clearVideo()
}
onMounted(() => {
// 调用摄像头
navigator.mediaDevices.getUserMedia({ video: true })
.then(stream => {
// 将摄像头捕捉到的视频流绑定到video元素上
video.value.srcObject = stream;
})
.catch(error => {
console.error(error);
});
})
</script>
<style></style>
Vue3中调用摄像头并拍照
最新推荐文章于 2024-06-28 18:07:00 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)