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" style="display:none;"></canvas>
<img :src="photo" v-if="photo" />
</div>
</template>
<script>
export default {
data() {
return {
photo: null,
stream: null
}
},
mounted() {
this.initCamera()
},
beforeDestroy() {
if (this.stream) {
this.stream.getTracks().forEach(track => track.stop())
}
},
methods: {
async initCamera() {
try {
this.stream = await navigator.mediaDevices.getUserMedia({
video: { facingMode: 'environment' } // 后置摄像头
})
this.$refs.video.srcObject = this.stream
} catch (err) {
console.error("摄像头访问失败:", err)
}
},
capture() {
const canvas = this.$refs.canvas
const video = this.$refs.video
canvas.width = video.videoWidth
canvas.height = video.videoHeight
canvas.getContext('2d').drawImage(video, 0, 0)
this.photo = canvas.toDataURL('image/png')
}
}
}
</script>
使用第三方库vue-web-cam
对于快速集成,可以使用现成的Vue组件:
安装:

npm install vue-web-cam
示例代码:
<template>
<div>
<web-cam 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>
移动端适配注意事项
在移动设备上需要添加viewport配置:
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
iOS Safari需要特殊处理:

// 解决iOS上视频不自动播放的问题
document.addEventListener('click', function() {
const video = document.querySelector('video')
if (video) video.play()
}, { once: true })
图片处理与上传
捕获后的图片可以转换为Blob进行上传:
function dataURLtoBlob(dataurl) {
const arr = dataurl.split(',')
const mime = arr[0].match(/:(.*?);/)[1]
const bstr = atob(arr[1])
let n = bstr.length
const u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
return new Blob([u8arr], { type: mime })
}
// 上传示例
const blob = dataURLtoBlob(this.photo)
const formData = new FormData()
formData.append('image', blob, 'photo.png')
权限处理
添加用户拒绝权限时的处理逻辑:
async initCamera() {
try {
this.stream = await navigator.mediaDevices.getUserMedia({
video: true
})
this.$refs.video.srcObject = this.stream
} catch (err) {
if (err.name === 'NotAllowedError') {
alert('请允许摄像头访问权限')
}
console.error(err)
}
}
样式优化
建议添加基础样式改善用户体验:
video {
width: 100%;
max-width: 500px;
background: #000;
margin: 0 auto;
display: block;
}
button {
display: block;
margin: 10px auto;
padding: 8px 16px;
}
img {
max-width: 100%;
display: block;
margin: 0 auto;
}






