一个简易的人脸登录验证,希望对需求者有帮助
基本原理:
1、通过浏览器相关api打开本地摄像头
2、把视频流传给video标签播放出来
3、通过canvas进行图片截取,生成图片,进行人脸比对
<template>
<div class="face-container">
<div class="face_k">
<video ref="video"></video>
</div>
<canvas width="200" height="150" ref="canvas"></canvas>
<button class="btn" @click="login">登陆</button>
</div>
</template>
<script>
export default {
name: 'login_face',
data() {
return {
video: '',
canvas: '',
mediaStreamTrack: ''
};
},
mounted() {
this.getStream();
},
beforeDestroy() {
this.cancalCloseVideo();
},
methods: {
cancalCloseVideo() {
this.mediaStreamTrack?.stop();
},
getStream() {
// H5调用电脑摄像头API
let videoObj = { video: true }; //打开摄像头
// 判断是否自持新版浏览器获取视频流的方法
// getUserMedia 会提示用户给予使用媒体输入的许可,接受参数打开摄像头、返回一个promise对象,
// 成功拿到一个视频流,把这个视频给video播放出来
if (navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices
.getUserMedia(videoObj)
.then(stream => {
this.$refs['video'].srcObject = stream;
this.$refs['video'].play();
})
.catch(function(err) {
console.log(err);
});
} else if (navigator.getUserMedia) {
navigator.webkitGetUserMedia(videoObj, function(stream) {
this.$refs['video'].src = window.URL.createObjectURL(stream);
this.$refs['video'].play();
});
} else if (navigator.mozGetUserMedia) {
navigator.mozGetUserMedia(videoObj, function(stream) {
this.$refs['video'].mozSrcObject = stream;
this.$refs['video'].play();
});
}
},
login() {
let ctx = this.$refs['canvas'].getContext('2d');
// 把当前视频帧内容渲染到canvas上
ctx.drawImage(this.$refs['video'], 0, 0, 400, 300);
// 转base64格式、图片格式转换、图片质量压缩
let imgBase64 = this.$refs['canvas'].toDataURL('image/jpeg', 0.7);
var blob = this.dataURLtoBlob(imgBase64);
var file = this.blobToFile(blob, Date.now());
//请求接口
/*
....
*/
},
//将图片转化blob
dataURLtoBlob(dataurl) {
var arr = dataurl.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
},
//将blob转换为file
blobToFile(theBlob, fileName) {
theBlob.lastModifiedDate = new Date();
theBlob.name = fileName;
return theBlob;
}
}
};
</script>
<style scoped>
.face-container {
display: flex;
flex-wrap: wrap;
}
canvas {
display: none;
}
.btn {
width: 100%;
height: 54px;
cursor: pointer;
margin: 20px auto;
}
img {
width: 318px;
height: 54px;
}
.face_k {
width: 600px;
margin: 0 auto;
height: 400px;
}
video {
width: 100%;
height: 100%;
padding: 0;
object-fit: fill;
}
.word {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
font-size: 20px;
font-family: FZLBJW--GB1-0, FZLBJW--GB1;
font-weight: normal;
color: rgba(30, 33, 38, 1);
}
.btn {
width: 90%;
height: 40px;
line-height: 40px;
border-radius: 5px;
border: none;
margin: 20px auto;
}
</style>