描述:
vue项目中,获取摄像头进行拍照,并对拍摄的图片进行旋转、裁剪等处理
html部分
<!-- 摄像头列表 -->
<el-select v-model="autoVal" size="small" @change="change('auto', true)">
<el-option
v-for="item in vidList"
:key="item.deviceId"
:value="item.deviceId"
:label="item.label"
/>
</el-select>
<!-- 拍照按钮 -->
<el-button size="small" type="primary" @click="getImg('auto')">拍照</el-button>
<!-- 拍照画面显示区 -->
<div id="right-bottom" v-loading="loading" class="right-bottom">
<video v-show="videoFalg" id="video" ref="videoElement" autoplay :srcObject="videoSource" />
<video v-show="false" id="videoElement" ref="video" autoplay :srcObject="videoSource" />
<img id="img" src="" alt="">
<div v-show="!a3Ora4 && !isNewModel" id="videoboder" class="videoboder" />
<canvas v-show="false" id="canvas" />
<!-- <video ref="videoElement" autoplay id="video"></video> -->
</div>
第一步:初始化
data() {
resolutionRatio: '2592x1944',
a3Ora4: false,
videoSource: null,
acrossOrvertical: true, // 横版
autoVal: '',
videoFalg: false,
constraints: {},
val: '',
loading: false,
imgLoading: false,
autoSelectedIndex: '',
vidList: [],
},
mounted() {
this.getMediaInfo()
},
methods: {
// 第一步
getMediaInfo() {
if (navigator.mediaDevices.getUserMedia || navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia) {
this.constraints = {
video: {
width: { ideal: 2592 },
height: { ideal: 1944 },
deviceId: ''
}
}
// 初始化
this.getUserMedia(this.constraints, this.deSuccess, this.error, '0')
} else {
alert('不支持访问用户媒体')
}
},
第二步:getUserMedia
getUserMedia(constraints, success, error, type) {
this.videoFalg = type !== '0'
if (navigator.mediaDevices.getUserMedia) {
// 最新的标准API
navigator.mediaDevices.getUserMedia(constraints)
.then(success)
.catch(error)
} else if (navigator.webkitGetUserMedia) {
// webkit核心浏览器
navigator.webkitGetUserMedia(constraints, success, error)
} else if (navigator.mozGetUserMedia) {
// firfox浏览器
navigator.mozGetUserMedia(constraints, success, error)
} else if (navigator.getUserMedia) {
// 旧版API
navigator.getUserMedia(constraints, success, error)
}
},
success(stream) {
const video = document.getElementById('video')
const el = document.getElementById('videoElement')
const videoElement = this.$refs.videoElement
// 兼容webkit核心浏览器
if (this.videoFalg) {
this.videoSource = stream
videoElement.srcObject = stream
el.srcObject = stream
}
this.loading = false
video.onloadedmetadata = (e) => {
video.play()
}
},
error(err) {
console.log(err)
},
deSuccess(stream) {
// 获取拍照设备列表
this.getDevice()
}
第三步,获取拍照设备列表
getDevice() {
if (!navigator.mediaDevices?.enumerateDevices) {
console.log('不支持')
} else {
navigator.mediaDevices
.enumerateDevices()
.then((devices) =>