vue 实现拍照功能
使用HTML5的getUserMedia API实现拍照
在Vue中实现拍照功能可以通过HTML5的getUserMedia API访问摄像头,结合canvas元素捕获图像。
安装依赖(如需处理图像):
npm install vue-web-cam # 可选,使用现成组件
基础实现代码示例
<template>
<div>
<video ref="video" autoplay></video>
<button @click="capture">拍照</button>
<canvas ref="canvas" width="640" height="480"></canvas>
<img :src="photo" v-if="photo" />
</div>
</template>
<script>
export default {
data() {
return {
photo: null,
stream: null
}
},
mounted() {
this.initCamera()
},
methods: {
async initCamera() {
try {
this.stream = await navigator.mediaDevices.getUserMedia({
video: { width: 640, height: 480 }
})
this.$refs.video.srcObject = this.stream
} catch (err) {
console.error('摄像头访问失败:', err)
}
},
capture() {
const canvas = this.$refs.canvas
const video = this.$refs.video
canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height)
this.photo = canvas.toDataURL('image/png')
}
},
beforeDestroy() {
if (this.stream) {
this.stream.getTracks().forEach(track => track.stop())
}
}
}
</script>
使用第三方组件vue-web-cam
对于快速实现,可以使用现成组件:
npm install vue-web-cam
实现代码:
<template>
<div>
<WebCam ref="webcam" />
<button @click="capture">拍照</button>
<img :src="photo" v-if="photo" />
</div>
</template>
<script>
import { WebCam } from 'vue-web-cam'
export default {
components: { WebCam },
data() {
return {
photo: null
}
},
methods: {
capture() {
this.photo = this.$refs.webcam.capture()
}
}
}
</script>
移动端适配注意事项
在移动设备上需要添加以下处理:
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
权限处理和安全考虑
现代浏览器要求所有媒体访问必须在安全上下文(HTTPS或localhost)中进行。需要处理用户拒绝权限的情况:
initCamera() {
navigator.mediaDevices.getUserMedia({ video: true })
.then(stream => {
this.stream = stream
this.$refs.video.srcObject = stream
})
.catch(err => {
if (err.name === 'NotAllowedError') {
alert('请允许摄像头访问权限')
}
console.error(err)
})
}
图像处理和保存
捕获的图像可以进一步处理或发送到服务器:
// 转换为Blob对象
canvas.toBlob(blob => {
const formData = new FormData()
formData.append('photo', blob, 'photo.png')
// 上传到服务器
axios.post('/api/upload', formData)
}, 'image/png')
样式优化建议
为视频和canvas元素添加基本样式:
video, canvas {
max-width: 100%;
height: auto;
background: #000;
}
以上实现方案涵盖了从基础实现到第三方组件使用的多种方式,可根据项目需求选择适合的方法。







