用navigator.mediadevices.getusermedia函数在vue上实现拍照功能,视频分辨率为1280*720
时间: 2024-04-29 14:24:21 浏览: 189
在Vue中实现拍照功能,需要先引入navigator.mediaDevices.getUserMedia()函数,然后在组件中调用该函数,传入分辨率参数,如下所示:
```
<template>
<div>
<video ref="video" autoplay></video>
<button @click="takePhoto">Take Photo</button>
<canvas ref="canvas"></canvas>
</div>
</template>
<script>
export default {
data() {
return {
videoWidth: 1280,
videoHeight: 720
}
},
mounted() {
this.initCamera()
},
methods: {
async initCamera() {
const stream = await navigator.mediaDevices.getUserMedia({
video: {
width: this.videoWidth,
height: this.videoHeight
}
})
this.$refs.video.srcObject = stream
},
takePhoto() {
const video = this.$refs.video
const canvas = this.$refs.canvas
canvas.width = this.videoWidth
canvas.height = this.videoHeight
const ctx = canvas.getContext('2d')
ctx.drawImage(video, 0, 0, this.videoWidth, this.videoHeight)
const dataURL = canvas.toDataURL('image/png')
console.log(dataURL)
}
}
}
</script>
```
在上面的代码中,我们定义了一个data属性videoWidth和videoHeight,用于指定视频的分辨率。在mounted钩子中调用initCamera函数,该函数通过navigator.mediaDevices.getUserMedia()函数获取视频流,并将其赋值给video标签的srcObject属性,从而实现摄像头预览。在takePhoto函数中,我们获取video和canvas标签,并设置canvas的宽度和高度为videoWidth和videoHeight。然后使用canvas的getContext()方法获取绘图上下文,调用drawImage()方法将video标签中的画面绘制到canvas上。最后,调用canvas的toDataURL()方法将canvas内容转换为base64编码的字符串,该字符串即为拍摄的照片数据。我们可以将该字符串保存到本地或上传到服务器进行处理。
阅读全文