elementui拍照
使用ElementUI实现拍照功能
ElementUI本身不直接提供拍照组件,但可以通过结合HTML5的<input type="file">和<video>元素实现。以下是实现方案:
基础实现方法
创建文件输入控件并限制为摄像头捕获
<el-button @click="openCamera">打开摄像头</el-button>
<input
ref="cameraInput"
type="file"
accept="image/*"
capture="camera"
style="display: none"
>
完整组件实现

<template>
<div>
<el-button @click="startCamera">开启摄像头</el-button>
<el-button @click="takePhoto" :disabled="!isCameraOpen">拍照</el-button>
<video ref="video" autoplay style="width: 300px"></video>
<canvas ref="canvas" style="display: none"></canvas>
<div v-if="photoData">
<img :src="photoData" style="max-width: 300px"/>
<el-button @click="savePhoto">保存照片</el-button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
isCameraOpen: false,
photoData: null,
stream: null
}
},
methods: {
async startCamera() {
try {
this.stream = await navigator.mediaDevices.getUserMedia({ video: true })
this.$refs.video.srcObject = this.stream
this.isCameraOpen = true
} catch (error) {
this.$message.error('摄像头访问失败: ' + error.message)
}
},
takePhoto() {
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)
this.photoData = canvas.toDataURL('image/png')
},
savePhoto() {
// 这里实现保存逻辑,如上传到服务器
this.$message.success('照片已保存')
},
beforeDestroy() {
if (this.stream) {
this.stream.getTracks().forEach(track => track.stop())
}
}
}
}
</script>
移动端适配方案
对于移动设备,建议添加方向检测:
takePhoto() {
const video = this.$refs.video
const canvas = this.$refs.canvas
// 检测设备方向
const isPortrait = window.innerHeight > window.innerWidth
canvas.width = isPortrait ? video.videoWidth : video.videoHeight
canvas.height = isPortrait ? video.videoHeight : video.videoWidth
const ctx = canvas.getContext('2d')
if (isPortrait) {
ctx.drawImage(video, 0, 0)
} else {
ctx.rotate(90 * Math.PI / 180)
ctx.drawImage(video, 0, -canvas.width)
}
this.photoData = canvas.toDataURL('image/jpeg', 0.8)
}
样式优化建议
使用ElementUI的Dialog组件创建拍照界面:

<el-dialog title="拍照" :visible.sync="showCameraDialog">
<video ref="video" autoplay style="width: 100%"></video>
<div slot="footer">
<el-button @click="takePhoto">拍照</el-button>
</div>
</el-dialog>
注意事项
-
需要HTTPS环境或在localhost下才能访问摄像头
-
iOS设备对摄像头分辨率有限制,建议设置约束:
const constraints = {
video: {
width: { ideal: 1280 },
height: { ideal: 720 },
facingMode: 'environment' // 后置摄像头
}
}
-
拍照质量可通过调整toDataURL参数控制:
// 质量参数0-1,格式可选image/jpeg或image/png
canvas.toDataURL('image/jpeg', 0.7)
以上方案结合了ElementUI的组件优势和HTML5媒体API,实现了完整的拍照功能。