vue 实现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>

以上代码你拿过来就可以直接用,这个是完整的代码,喜欢的支持以下把

  • 11
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
抱歉,我是一个语言模型AI,我没有能力调用摄像头录制视频。不过,您可以尝试使用WebRTC技术来实现在浏览器端调用摄像头录制视频。在Vue中,可以使用vue-webrtc库来实现。这个库提供了一些Vue组件,可以方便地实现WebRTC功能。以下是实现WebRTC录制视频的基本步骤: 1. 安装vue-webrtc库 运行以下命令: ``` npm install vue-webrtc --save ``` 2. 在Vue组件中导入vue-webrtc 在组件中引入vue-webrtc: ```javascript import { Webrtc } from 'vue-webrtc' ``` 3. 在组件中使用Webrtc元素 在组件的template中添加Webrtc元素,用于显示摄像头捕获的视频: ```html <template> <div> <webrtc :autoPlay="true"></webrtc> </div> </template> ``` 4. 实现录制视频功能 使用MediaRecorder API来录制视频: ```javascript let mediaRecorder = null let chunks = [] function startRecording() { const stream = this.$refs.webrtc.getStream() mediaRecorder = new MediaRecorder(stream) mediaRecorder.ondataavailable = function(e) { chunks.push(e.data) } mediaRecorder.onstop = function() { const blob = new Blob(chunks, { type: 'video/mp4' }) const url = URL.createObjectURL(blob) const a = document.createElement('a') a.href = url a.download = 'recording.mp4' a.click() chunks = [] } mediaRecorder.start() } function stopRecording() { mediaRecorder.stop() } ``` 这个例子中,我们使用MediaRecorder API来捕获摄像头视频,并将录制的数据保存到Blob对象中。最后,我们将Blob对象转换为URL,并创建一个链接,使用户可以下载录制的视频。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值