VUE PC端调用USB摄像头(复制即用)

以下为vue代码。粘贴即可使用(亲身经历)。可用于封装页面等。

<template>
  <div>
    <div>
      <div class="box">
        <!-- 这个是显示的图像-->
        <video id="videoCamera" class="canvas" :width="videoWidth" :height="videoHeight" autoPlay></video>
      </div>
      <div>
        <!-- 这个只所以隐藏就是因为下面有显示的img-->
        <canvas id="canvasCamera" class="canvas" :width="videoWidth" :height="videoHeight" hidden></canvas>
      </div>
    </div>
    <div>
      <div slot="footer">
        <el-button icon="el-icon-camera" size="small" @click="drawImage">拍照</el-button>
      </div>
    </div>
    <el-form>
      <!--拍照后显示图片-->
      <el-form-item>
        <div v-for="src in imgSrc" :key="src" style="display: flex; flex-direction: column;"> 

          <img ref="esign" :src="src" 
               style="width: 300px; height: 200px;" @click="naImage(src)"
          />
 
        </div>
      </el-form-item>
    </el-form>
 
  </div>
</template>
<script>
// import { uploadImg } from "@/api/interface";
 
export default {
  name: "Video",
  data() {
    return {
     // imgSrc: "", // 默认值为空s
     imgSrc:[],
      os: false, //控制摄像头开关
      thisVideo: null,
      thisContext: null,
      thisCancas: null,
      videoWidth: 300,
      videoHeight: 200,
    };
  },
  created() {},
  mounted(){
//这个是页面已加载就会触发这个方法
    this.getCompetence();
  },
  methods: {
    // 调用摄像头权限
    getCompetence() {
      this.$nextTick(() => {
        const _this = this;
        this.os = false; 
        this.thisCancas = document.getElementById("canvasCamera");
        this.thisContext = this.thisCancas.getContext("2d");
        this.thisVideo = document.getElementById("videoCamera");
        if (navigator.mediaDevices === undefined) {
          navigator.menavigatordiaDevices = {};
        }
        if (navigator.mediaDevices.getUserMedia === undefined) {
          navigator.mediaDevices.getUserMedia = function (constraints) {
            let getUserMedia =
              navigator.webkitGetUserMedia ||
              navigator.mozGetUserMedia ||
              navigator.getUserMedia;
            if (!getUserMedia) {
              return Promise.reject(
                new Error("getUserMedia is not implemented in this browser")
              );
            }
            return new Promise(function (resolve, reject) {
              getUserMedia.call(navigator, constraints, resolve, reject);
            });
          };
        }
        const constraints = {
          audio: false,
          video: {
            width: _this.videoWidth,
            height: _this.videoHeight,
            transform: "scaleX(-1)",
          },
        };
        navigator.mediaDevices
          .getUserMedia(constraints)
          .then(function (stream) {
            if ("srcObject" in _this.thisVideo) {
              _this.thisVideo.srcObject = stream;
            } else {
              _this.thisVideo.src = window.URL.createObjectURL(stream);
            }
            _this.thisVideo.onloadedmetadata = function (e) {
              _this.thisVideo.play();
            };
          })
          .catch((err) => {
            this.$notify({
              title: "警告",
              message: "没有开启摄像头权限或浏览器版本不兼容.",
              type: "warning",
            });
          });
      });
    },
    //绘制图片
    async drawImage() {
      this.thisContext.drawImage(
        this.thisVideo,
        0,
        0,
        this.videoWidth,
        this.videoHeight
      );
      // 获取图片base64链接
      //this.imgSrc = this.thisCancas.toDataURL("image/png");
      const newImgSrc = this.thisCancas.toDataURL("image/png");
      this.imgSrc.push(newImgSrc); 
    },
    naImage(src){
      console.log("图片的地址",src);
      //把这个图片转换成base64
      let arr = src.split(",");
        let array = arr[0].match(/:(.*?);/);
        let mime = (array && array.length > 1 ? array[1] : type) || type;
        // 去掉url的头,并转化为byte
        let bytes = window.atob(arr[1]);
        // 处理异常,将ascii码小于0的转换为大于0
        let ab = new ArrayBuffer(bytes.length);
        // 生成视图(直接针对内存):8位无符号整数,长度1个字节
        let ia = new Uint8Array(ab);
        for (let i = 0; i < bytes.length; i++) {
          ia[i] = bytes.charCodeAt(i);
        }
        const randomNumber = Math.floor(1000 + Math.random() * 9000);
        const fileNameJPG = `图片${randomNumber}.jpg`;
        let formData = new FormData();
        formData.append(
          "file",
          new File([ia], fileNameJPG, { type: mime })
        );
 
        //上传图片接口
        // uploadImg(formData).then((res) => {
        //   console.log(res.filePaths,'哈哈哈');
        // });
    },
 
  },
};
</script>

<style scoped>

.canvas{
height: 30%;
width: 30%;

}

</style>

总结

使用该代码即可调用。最后的CSS用于控制显示的摄像头内容区域的大小。欢迎大家随时交流

  • 10
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在 Vue 项目中调用 USB 摄像头,你需要使用 WebRTC 技术。WebRTC 是一种用于在浏览器中实现实时通信的技术,其中包括视频通话、音频通话和数据传输等功能。以下是一些步骤,可以帮助你实现在 Vue 项目中调用 USB 摄像头: 1. 首先,你需要在 Vue 项目中安装 webrtc-adapter 库。你可以通过运行以下命令来安装它: ``` npm install webrtc-adapter --save ``` 2. 接下来,你需要使用 getUserMedia() 方法获取摄像头的视频流。该方法是 WebRTC API 的一部分,可以用于获取媒体设备的权限并捕获视频流。你可以使用以下代码: ```javascript navigator.mediaDevices.getUserMedia({ video: true }) .then(stream => { // stream是媒体流,可以用于展示视频等操作 }) .catch(error => { console.error('Error accessing media devices.', error); }); ``` 3. 你可以在 Vue 组件中使用上述代码来获取视频流,并将其展示在页面上。例如,你可以创建一个 video 标签,并使用 JavaScript 将视频流绑定到该标签中: ```vue <template> <div> <video ref="video" autoplay></video> </div> </template> <script> export default { mounted() { navigator.mediaDevices.getUserMedia({ video: true }) .then(stream => { this.$refs.video.srcObject = stream; }) .catch(error => { console.error('Error accessing media devices.', error); }); } } </script> ``` 4. 最后,你需要在页面中添加一些样式,以便正确显示视频流。例如,你可以使用以下 CSS 样式: ```css video { width: 100%; height: auto; } ``` 这些步骤应该可以帮助你在 Vue 项目中调用 USB 摄像头

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值