vue 实现pc端调用摄像头进行拍照(用于PC端人像采集,兼容浏览器,复制就可以运行)

<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 @click="drawImage" icon="el-icon-camera" size="small">拍照</el-button>
        </div>
    </div>
    <el-form>
      <!--拍照后显示图片-->
      <el-form-item>
        <div style="display: flex; flex-direction: column;"> 
        <template v-for="src in imgSrc">
          <img :src="src" ref="esign"
           style="width: 300px; height: 200px;" @click="naImage(src)"/>
        </template>
      </div>
      </el-form-item>
    </el-form>
 
  </div>
</template>
<script>
import { uploadImg } from "@/api/interface";
 
export default {
  name: "Camera",
  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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值