vue mediaDevices 驱动摄像头

2019-06-06  本文已影响0人  吴占超

为了实现二维码h5扫描 进行的 第一步测试
重点:需要开启https
vue.config.js 设置开启https

  devServer: {
    // 前端端口
    port: 8080,
    // 代理地址
    // proxy: 'http://g5rdyr.ngrok.io'
    proxy: 'http://localhost:8090',
    https: true
  },
<template>
  <v-container grid-list-md>
    <v-layout row wrap align-center justify-space-between>
      <v-flex xs12>
        <!-- <video ref="video" id="video" autoplay></video> -->
        <video ref="video" width="320" height="240" controls></video>
      </v-flex>
      <v-flex xs12>
        <canvas ref="canvas" width="320px" height="240px"></canvas>
      </v-flex>
      <v-flex xs6>
        <button type="button" class="btn btn-info" @click="camera('environment')">Back Camera</button>
      </v-flex>
      <v-flex xs6>
        <button type="button" class="btn btn-info" @click="camera('user')">front Camera</button>
      </v-flex>
    </v-layout>
  </v-container>
</template>

<script>
/**
 * 摄像头控制 demo
 */
export default {
  data: () => ({
    video: {},
    localstream: undefined
  }),
  methods: {
    camera (face) {
      this.stop();
      this.gum(face);
    },
    stop () {
      return this.video.srcObject && this.video.srcObject.getTracks().map(t => t.stop());
    },
    gum (face) {
      const fa = face === 'user' ? { facingMode: 'user' } : { facingMode: { exact: 'environment' } };
      return navigator.mediaDevices.getUserMedia({ audio: false, video: fa })
        .then(stream => {
          this.$refs.video.srcObject = stream;
          this.$refs.video.play();
        }).catch(() => {
          navigator.mediaDevices.getUserMedia({ audio: false, video: true })
            .then(stream => {
              this.$refs.video.srcObject = stream;
              this.$refs.video.play();
            });
        });
    }
  },
  mounted () {
    this.camera('environment');
  }
};
</script>

<style lang="scss" scoped>
</style>

上一篇下一篇

猜你喜欢

热点阅读