vue调用摄像头

<template>
   <video
        v-else
        id="local_video"
        autoplay
      ></video>
      <canvas
        width="720px"
        height="720px"
        style="display: none"
        id="canvas"
      ></canvas>
</template>

data () {
  return {
    // 摄像头列表
     videoArr: [],
     webStream : null,
     params: new FormData()
  }
}
// 获取摄像头列表
await navigator.mediaDevices.enumerateDevices({
                audio: false,
                video: true,
              })
                .then((devices) => {
                  devices.forEach((device) => {
                    if (device.kind == 'videoinput') {
                      videoArr.push({
                        'label': device.label,
                        'id': device.deviceId
                      })
                    }
                  });
                })


//  摄像头显示图像
showVideo () {
      navigator.mediaDevices
        .getUserMedia({
          audio: false,
          video: {
            deviceId: {
              exact: this.videoArr[0].id
            }
          }
        })
        .then((data) => {
            this.webStream = data
            document.getElementById('local_video').srcObject = this.webStream
        })
        .catch((error) => {
          this.$message({
            message: '未连接摄像头',
            type: 'error',
          })
        })
    },

// 传输图片
takePhoto () {
    const canvas = document.getElementById('canvas')
      var ctx = canvas.getContext('2d')
      ctx.drawImage(document.getElementById('local_video'), 0, 0, 720, 720)
      let file = this.dataURItoBlob(canvas.toDataURL('image/png').replace('image/png', 'image/octet-stream'))
      let fm = new FormData()
      fm.append('file', file)
      // 接口
     upload(fm).then((res) => {
        console.log(res)
     })
}

// 传输视频
takeVideo() {
     const mine = MediaRecorder.isTypeSupported('video/webm;codecs=vp9') ? 'video/webm;codecs=vp9' : 'video/webm'
     const mediaRecorder = new MediaRecorder(this.webStream, { mimeType: mine })
     var recordedChunks = [];
     mediaRecorder.ondataavailable = (event) => {
         const buffer = [event.data]
         recordedChunks.push(new Blob(buffer, { type: 'video/webm' }))
     }
     // 每次间隔100毫秒
      mediaRecorder.start(100)
      setTimeout(() => {
      // 关闭录制功能
      mediaRecorder.stop()
      const fileStream = new File(recordedChunks, '1234.webm')
      this.params.append('file', fileStream)
   // 录制1秒钟视频
   }, 1000)
    // 接口
   upload(this.params).then((res) => {
       console.log(res,)
   })
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容