一.该案例情况
框架:vue;
运行环境:PC;
二.准备
在pc端中需要使用https地址才可以访问到摄像头流信息,
所以在生产环境中,我们可以通过vue.config.js来配置localhost的https地址
在正式环境中,可以给域名配置https证书达到要求,所以影响不大
vue.config.js主要代码
/* webpack配置 */ var path = require('path') function resolve (pathUrl){ return path.resolve(__dirname,pathUrl) } module.exports = { devServer: { // 前端端口 port: 8080, // 代理地址 // proxy: 'http://g5rdyr.ngrok.io' proxy: 'http://localhost:8081', https: true }, }
三.写代码(app.vue)
<template> <div id="app"> <video ref="video" id="video" width="320" height="240" controls></video> <canvas id="canvas" ref="canvas" width="320px" height="240px"></canvas> <button type="button" class="btn btn-info" @click="camera('environment')">Back Camera</button> <button type="button" class="btn btn-info" @click="camera('user')">front Camera</button> </div> </template>
<script> export default { name: 'app', data() { return { video: {}, localstream: undefined } }, mounted() { this.$nextTick(()=>{ this.camera('environment'); }) }, 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 => { console.log(stream) let video = document.getElementById("video"), canvas = document.getElementById("canvas"), context = canvas.getContext("2d"), vHeight = video.offsetHeight, vWidth = video.offsetWidth; canvas.width = vWidth; // 改变画布的宽高 canvas.height = vHeight; context.drawImage(video, 0, 0, vWidth, vHeight); // 获取图片src base64格式 photoSrc = document.getElementById("canvas").toDataURL("image/jpeg", 0.8); console.log(photoSrc) 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(); }); }); } } } </script>
四.效果
1.进入页面
2.点击camera按钮拍照