Vue+tracking.js 实现前端人脸检测功能

2020-06-16 06:57:49易采站长站整理

await navigator.mediaDevices
.getUserMedia(this.userMediaConstraints)
.then(this.getMediaStreamSuccess)
.catch(this.getMediaStreamError)
await this.onPlay()
},
async onPlay() {
debugHelper.log('onPlay')

this.onTrackTracking()
},
changeView() {
this.setTitle('刷脸登陆')
this.setBackDisabled(false)
this.setBackIcon('arrow_back')
msgbus.vm.setBottomNavVisible(false)
msgbus.vm.setBottomBtnVisible(false)
msgbus.vm.setMsgInputVisible({ value: false })
},

onTrackTracking() {
const context = this
const video = this.videoEl
const canvas = this.canvasEL
const canvasContext = canvas.getContext('2d')
let tracker = new tracking.ObjectTracker('face')

video.pause()
video.src = ''
tracker.setInitialScale(4)
tracker.setStepSize(2)
tracker.setEdgesDensity(0.1)
tracking.track('#video_cam', tracker, { camera: true })
tracker.on('track', function(event) {
const { autoCaptureTrackTraking } = context
canvasContext.clearRect(0, 0, canvas.width, canvas.height)
event.data.forEach(function({ x, y, width, height }) {
canvasContext.strokeStyle = '#a64ceb'
canvasContext.strokeRect(x, y, width, height)
canvasContext.font = '11px Helvetica'
canvasContext.fillStyle = '#fff'
})

if (!isEmpty(event.data) && context.count <= 10) {
if (context.count < 0) context.count = 0
context.count += 1
//debugHelper.log(context.count)
if (context.count > 10) {
context.isdetected = '已检测到人脸,正在登录'
//context.$router.push({ name: 'pwdlogin' })
}
} else {
context.count -= 1
if (context.count < 0) context.isdetected = '请您保持脸部在画面中央'
//this.isdetected = '已检测到人脸,正在登录'
}

})
},
onDownloadFile(item) {
const link = document.createElement('a')
link.href = item
link.download = `cahyo-${new Date().toISOString()}.png`
link.click()

link.remove()
},
onTakeCam() {
const canvas = document.createElement('canvas')
const video = this.$el.querySelector('#video_cam')
const canvasContext = canvas.getContext('2d')

if (video.videoWidth && video.videoHeight) {
const isBiggerW = video.videoWidth > video.videoHeight
const fixVidSize = isBiggerW ? video.videoHeight : video.videoWidth
let offsetLeft = 0
let offsetTop = 0

if (isBiggerW) offsetLeft = (video.videoWidth - fixVidSize) / 2
else offsetTop = (video.videoHeight - fixVidSize) / 2

// make canvas size 300px
canvas.width = canvas.height = 300
const { width, height } = canvas

canvasContext.drawImage(
video,
offsetLeft,
offsetTop,
fixVidSize,
fixVidSize,
0,
0,
width,
height
)
const image = canvas.toDataURL('image/png')