vue 调用摄像头 Demo2

代码

html

1
2
<video id="videoCamera" :width="videoWidth" :height="videoHeight" autoplay></video>
<canvas style="display: none" id="canvasCamera" :width="videoWidth" :height="videoHeight"></canvas>

  

js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// 前面省略几万字<br><br>// 调用权限(打开摄像头功能)
getCompetence() {
  var _this = this;
  _this.thisCancas = document.getElementById("canvasCamera");
  _this.thisContext = this.thisCancas.getContext("2d");
  _this.thisVideo = document.getElementById("videoCamera");
  _this.thisVideo.style.display = "block";
  // 获取媒体属性,旧版本浏览器可能不支持mediaDevices,我们首先设置一个空对象
  if (navigator.mediaDevices === undefined) {
    navigator.mediaDevices = {};
  }
  // 一些浏览器实现了部分mediaDevices,我们不能只分配一个对象
  // 使用getUserMedia,因为它会覆盖现有的属性。
  // 这里,如果缺少getUserMedia属性,就添加它。
  if (navigator.mediaDevices.getUserMedia === undefined) {
    navigator.mediaDevices.getUserMedia = function (constraints) {
      // 首先获取现存的getUserMedia(如果存在)
      var getUserMedia =
        navigator.webkitGetUserMedia ||
        navigator.mozGetUserMedia ||
        navigator.getUserMedia;
      // 有些浏览器不支持,会返回错误信息
      // 保持接口一致
      if (!getUserMedia) {
        //不存在则报错
        return Promise.reject(
          new Error("getUserMedia is not implemented in this browser")
        );
      }
      // 否则,使用Promise将调用包装到旧的navigator.getUserMedia
      return new Promise(function (resolve, reject) {
        getUserMedia.call(navigator, constraints, resolve, reject);
      });
    };
  }
  var constraints = {
    audio: false,
    video: {
      width: this.videoWidth,
      height: this.videoHeight,
      transform: "scaleX(-1)",
    },
  };
  navigator.mediaDevices
    .getUserMedia(constraints)
    .then(function (stream) {
      // 旧的浏览器可能没有srcObject
      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) => {
      console.log(err);
    });
},

  

作者:假装空白
欢迎任何形式的转载,但请务必注明出处。
限于本人水平,如果文章和代码有表述不当之处,还请不吝赐教。

posted @   假装空白  阅读(280)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示