vue实现拍照录像
Vue 实现拍照功能
使用HTML5的<input type="file">结合capture属性可以实现拍照功能。在Vue中可以这样实现:

<template>
<div>
<input type="file" accept="image/*" capture="camera" @change="handleImageCapture">
<img v-if="capturedImage" :src="capturedImage" alt="Captured Image">
</div>
</template>
<script>
export default {
data() {
return {
capturedImage: null
}
},
methods: {
handleImageCapture(event) {
const file = event.target.files[0]
if (file) {
this.capturedImage = URL.createObjectURL(file)
}
}
}
}
</script>
Vue 实现录像功能
使用HTML5的<input type="file">结合capture属性也可以实现录像功能:

<template>
<div>
<input type="file" accept="video/*" capture="camcorder" @change="handleVideoCapture">
<video v-if="capturedVideo" :src="capturedVideo" controls></video>
</div>
</template>
<script>
export default {
data() {
return {
capturedVideo: null
}
},
methods: {
handleVideoCapture(event) {
const file = event.target.files[0]
if (file) {
this.capturedVideo = URL.createObjectURL(file)
}
}
}
}
</script>
使用媒体设备API实现更高级功能
如果需要更高级的控制,可以使用浏览器的媒体设备API:
<template>
<div>
<video ref="video" autoplay></video>
<button @click="captureImage">拍照</button>
<button @click="startRecording">开始录像</button>
<button @click="stopRecording">停止录像</button>
<img v-if="photo" :src="photo" alt="Captured Photo">
<video v-if="recordedVideo" :src="recordedVideo" controls></video>
</div>
</template>
<script>
export default {
data() {
return {
stream: null,
photo: null,
recordedVideo: null,
mediaRecorder: null,
recordedChunks: []
}
},
methods: {
async startCamera() {
try {
this.stream = await navigator.mediaDevices.getUserMedia({ video: true })
this.$refs.video.srcObject = this.stream
} catch (err) {
console.error('Error accessing camera:', err)
}
},
captureImage() {
const canvas = document.createElement('canvas')
canvas.width = this.$refs.video.videoWidth
canvas.height = this.$refs.video.videoHeight
canvas.getContext('2d').drawImage(this.$refs.video, 0, 0, canvas.width, canvas.height)
this.photo = canvas.toDataURL('image/png')
},
startRecording() {
this.recordedChunks = []
this.mediaRecorder = new MediaRecorder(this.stream, { mimeType: 'video/webm' })
this.mediaRecorder.ondataavailable = event => {
if (event.data.size > 0) {
this.recordedChunks.push(event.data)
}
}
this.mediaRecorder.onstop = () => {
const blob = new Blob(this.recordedChunks, { type: 'video/webm' })
this.recordedVideo = URL.createObjectURL(blob)
}
this.mediaRecorder.start()
},
stopRecording() {
this.mediaRecorder.stop()
}
},
mounted() {
this.startCamera()
},
beforeDestroy() {
if (this.stream) {
this.stream.getTracks().forEach(track => track.stop())
}
}
}
</script>
注意事项
不同浏览器对媒体API的支持程度不同,建议在实际使用时添加兼容性检查。移动设备上可能需要HTTPS环境才能正常使用摄像头功能。
对于更复杂的需求,可以考虑使用第三方库如vue-web-cam或quasar框架提供的摄像头组件。






