点击打开相机按钮,弹出相机拍照弹窗,点击拍照按钮,截取录像的帧,在浏览器显示截取的录像的帧。
#
#
#
给 video 配置 muted 属性 使其静音自动播放,参考看
<template>
<div>
<img style="display: none" ref="photo" />
<el-button type="info" style="margin-top: 10px" @click="handleOpen">打开相机</el-button>
<!-- 弹窗 -->
<el-dialog v-model="dialogVisible" title="照片" width="50%">
<div>
<video ref="video" width="500" height="500" muted></video>
</div>
<el-button type="info" @click="submitImg">拍照</el-button>
</el-dialog>
</div>
</template>
直接写拍照功能的方法,参考看
<script setup>
import { ref, computed } from 'vue'
let video = ref() // 获取video的DOM
let dialogVisible = ref()
// 调起摄像头
const handleOpen = async () => {
dialogVisible.value = true
try {
// 调起摄像头
const stream = await navigator.mediaDevices.getUserMedia({ video: true })
// 也可以调摄像头的比例
// const stream = await navigator.mediaDevices.getUserMedia({ video: { width: 300,height: 400 }})
const videoElement = video.value
// 将摄像头画面绑定到 video 元素上
videoElement.srcObject = stream
videoElement.play()
} catch (error) {
console.error('无法访问摄像头:', error)
}
}
// 点击确认
let photo = ref() // 获取img的DOM
const submitImg = () => {
dialogVisible.value = false
// 创建一个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转换为图片,这时候的图片格式是base64,如果需要什么格式,需要另外进行转换
photo.value.src = canvas.toDataURL('image/png')
// 如果使用formData的话
// let formData = new FormData()
// formData.append('picture', photo.value.src)
// 如果使用formdata,那么接口需要添加 headers: {'Content-Type': 'multipart/form-data'}
// 显示图片
photo.value.style.display = 'block'
clearVideo()
}
const clearVideo = () => {
// 关闭摄像头
const stream = video.value.srcObject
const tracks = stream.getTracks()
tracks.forEach((track) => {
track.stop()
})
video.value.srcObject = null
}
</script>