这次公司得项目需求,让我完成一个功能,当有电脑摄像头时,就使用,如果没有那么就使用屏幕得录像功能
首先是语法:
可以参考一下MDN
this.变量
得地方,均是再 data
中定义过得 //拿到 摄像头 媒体流
async getUserMedia() {
console.log(`Requesting video stream`)
if ('mediaDevices' in navigator || navigator.mediaDevices) {
try {
const stream = await navigator.mediaDevices.getUserMedia(this.constraints)
this.myVideo.srcObject = stream
this.localStream = stream
this.track = typeof stream.stop === 'function' ? stream : stream.getTracks()[1]
console.log('onloadedmetadata' in this.myVideo)
} catch (error) {
console.log(`getUserMedia error: ${error}`)
}
}
},
// 拿到 屏幕录制 媒体流
async getDisplayMedia() {
if (!navigator.mediaDevices && !navigator.mediaDevices.getDisplayMedia) {
alert('当前浏览器不支持屏幕捕捉')
return
}
this.reset()
try {
this.mediaStream = await navigator.mediaDevices.getDisplayMedia({
audio: true,
video: true
})
this.myVideo.srcObject = this.mediaStream
this.mediaRecord = new MediaRecorder(this.mediaStream, {
audioBitsPerSecond: 128000,
videoBitsPerSecond: 2500000,
mimeType: 'video/webm;codecs=vp9'
})
this.mediaRecord.ondataavailable = function (e) {
if (e.data.size > 0) {
this.videoBuffer.push(e.data)
// this.$refs.downloadButton.removeAttribute('disabled')
}
}
// this.recorder.start()
// console.log(this.recorder)
// this.recorder.ondataavailable = this.recorder_dataAvailableHandler.bind(this)
} catch (error) {
console.log(error)
}
},
//截图
snapshot() {
let canvas = this.$refs.picture
canvas.width = 300
canvas.height = 250
canvas.getContext('2d').drawImage(this.myVideo, 0, 0, canvas.width, canvas.height)
let dataURL = canvas.toDataURL('image/jpg')
this.generateImages(dataURL)
},
// 保存图片
saveImg(item) {
let alink = document.createElement('a')
alink.href = item
let date = new Date()
let pic = dayjs(date).format('YYYYMMDDHHmmss')
alink.download = pic //图片名
alink.click()
},
// 生成图片
generateImages(dataURL) {
this.imgItems.push(dataURL)
this.saveImg(dataURL)
}