vue实现摄像功能
使用Vue实现摄像功能
在Vue中实现摄像功能可以通过浏览器的MediaDevices API完成。以下是具体实现方法:
获取摄像头权限并显示视频流
<template>
<div>
<video ref="video" autoplay playsinline></video>
<button @click="startCamera">开启摄像头</button>
<button @click="stopCamera">关闭摄像头</button>
<button @click="capture">拍照</button>
<canvas ref="canvas" style="display: none;"></canvas>
</div>
</template>
<script>
export default {
data() {
return {
stream: null
}
},
methods: {
async startCamera() {
try {
this.stream = await navigator.mediaDevices.getUserMedia({
video: true,
audio: false
})
this.$refs.video.srcObject = this.stream
} catch (err) {
console.error('摄像头访问失败:', err)
}
},
stopCamera() {
if (this.stream) {
this.stream.getTracks().forEach(track => track.stop())
this.$refs.video.srcObject = null
this.stream = null
}
},
capture() {
const video = this.$refs.video
const canvas = this.$refs.canvas
canvas.width = video.videoWidth
canvas.height = video.videoHeight
canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height)
// 获取图片数据
const imageData = canvas.toDataURL('image/png')
console.log(imageData)
// 可以在这里处理图片数据,如上传或显示
}
},
beforeDestroy() {
this.stopCamera()
}
}
</script>
处理不同摄像头设备
如果需要切换前后摄像头,可以修改getUserMedia参数:
async startCamera(facingMode = 'user') {
try {
this.stream = await navigator.mediaDevices.getUserMedia({
video: { facingMode },
audio: false
})
this.$refs.video.srcObject = this.stream
} catch (err) {
console.error('摄像头访问失败:', err)
}
}
调用时传入'environment'切换为后置摄像头:
<button @click="startCamera('environment')">使用后置摄像头</button>
添加拍照效果
可以在拍照时添加闪光效果:
capture() {
const videoContainer = this.$refs.video.parentElement
const flash = document.createElement('div')
flash.style.position = 'absolute'
flash.style.top = '0'
flash.style.left = '0'
flash.style.width = '100%'
flash.style.height = '100%'
flash.style.backgroundColor = 'white'
flash.style.opacity = '0'
videoContainer.appendChild(flash)
flash.animate([
{ opacity: 0 },
{ opacity: 1 },
{ opacity: 0 }
], { duration: 300 })
setTimeout(() => {
const video = this.$refs.video
const canvas = this.$refs.canvas
canvas.width = video.videoWidth
canvas.height = video.videoHeight
canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height)
videoContainer.removeChild(flash)
const imageData = canvas.toDataURL('image/png')
this.$emit('captured', imageData)
}, 150)
}
注意事项
- 确保在HTTPS环境下或localhost开发环境中使用摄像头API
- 调用
getUserMedia前需要用户授权 - 使用
beforeDestroy生命周期钩子确保组件销毁时关闭摄像头 - 移动端设备可能需要
playsinline属性使视频在页面内播放 - 不同浏览器对摄像头API的支持程度可能不同







