下载tracking.js
image.png注意:静态文件只需要build,复制build到项目的assets文件目录中,按需引入
<template>
<div class="face">
<div class="face-meiti">
<div class="tip">{{tip}}</div>
<video ref="video" width="200" height="200" preload autoplay loop muted playsinline :webkit-playsinline="true"></video>
<canvas ref="canvas" width="320" height="240"></canvas>
</div>
<img :src="src" alt="">
<p>{{getUserMedia}}</p>
</div>
</template>
<script>
import tracking from '@/assets/tracking/tracking-min.js';
import '@/assets/tracking/data/face-min.js';
export default {
data() {
return {
tip:'请正对摄像头',
mediaStreamTrack:null,
video:null,// 播放器实例
trackerTask:null, //tracking实例
uploadLock: true, // 上传锁
faceflag:false,//是否进行拍照
src:'',
getUserMedia:''
}
},
mounted() {
this.init();
},
methods: {
init() {
const _this = this;
this.video = this.mediaStreamTrack = this.$refs.video;
let canvas = this.$refs.canvas;
let context = canvas.getContext('2d', {willReadFrequently: true});
// this.getUserMedia = navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
//
// navigator.getUserMedia({'video':true},function (stream) {
// _this.video.srcObject = stream
// },function (err) {
// console.error('摄像头调用失败')
// })
this.initTracker(canvas, context)
},
initTracker(canvas, context){
const _this = this;
// 固定写法
let tracker = new window.tracking.ObjectTracker('face');
tracker.setInitialScale(4);
tracker.setStepSize(2);
tracker.setEdgesDensity(0.1);
// //摄像头初始化
this.trackerTask = window.tracking.track(this.video, tracker, {
camera: true
});
tracker.on('track', function (event){
if(event.data.length == 0){
if(!_this.faceflag){
_this.tip = '未检测到人脸'
}
}else if(event.data.length > 0){
_this.tip = '识别成功,正在拍照,请勿乱动~';
event.data.forEach(function(rect) {
context.strokeStyle = '#a64ceb';
context.strokeRect(rect.x, rect.y, rect.width, rect.height);
if(!_this.faceflag){// 检测到人脸进行拍照,延迟两秒
_this.faceflag = true
context.drawImage(_this.video, 0, 0, canvas.width, canvas.height);
let base64Img = canvas.toDataURL('image/jpeg');
_this.src = base64Img
setTimeout(function (){
_this.faceflag = false
}, 2000)
}
});
}
// else{
// _this.tip = '请处于相对空旷的环境'
// }
})
}
}
}
</script>
<style lang="scss">
.face{
.face-meiti{
position: relative;
.tip{
text-align: center;
font-size: 12px;
padding-bottom: 15px;
}
video{
width: 200px;
height: 200px;
-webkit-border-radius: 150px;
-moz-border-radius: 150px;
border-radius: 150px;
object-fit: cover;
border: 2px solid #000;
box-sizing: border-box;
}
canvas{
position: fixed;
left: 100vw;
top: 0;
z-index: -1;
width: 200px;
height: 200px;
background: #000;
}
}
img{
width: 100%;
height: auto;
}
}
</style>
网友评论