Skip to content

Instantly share code, notes, and snippets.

@RRanddom
Last active March 23, 2018 08:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RRanddom/ef2a1dda08d2c416beca70905fda30d7 to your computer and use it in GitHub Desktop.
Save RRanddom/ef2a1dda08d2c416beca70905fda30d7 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=yes, initial-scale=1, maximum-scale=1">
<meta itemprop="name" content="face-detect">
<meta name="mobile-web-app-capable" content="yes">
<meta id="theme-color" name="theme-color" content="#ffffff">
<title>Chrome Api 人脸检测</title>
<link href="//fonts.googleapis.com/css?family=Roboto:300,400,500,700" rel="stylesheet" type="text/css">
</head>
<body>
<div id="container">
<h1>人脸检测</h1>
<video autoplay></video>
<canvas></canvas>
</div>
</body>
<script>
'use strict';
var video = document.querySelector('video');
var canvas = document.querySelector('canvas');
canvas.width = 480;
canvas.height = 360;
var constraints = {
audio: false,
video: true
};
function handleSuccess(stream) {
window.stream = stream;
video.srcObject = stream;
}
function handleError(error) {
console.log('navigator.getUserMedia error: ', error);
}
navigator.mediaDevices.getUserMedia(constraints).
then(handleSuccess).catch(handleError);
function faceDetect(faceImage) {
if (window.FaceDetector == undefined) {
console.error('Face Detection not supported');
return;
}
var faceDetector = new FaceDetector();
var scale = 1;
return faceDetector.detect(video)
.then(faces => {
const width = video.videoWidth;
const height = video.videoHeight;
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.clearRect(0,0, width, height);
ctx.drawImage(video, 0, 0, width, height);
ctx.lineWidth = 1;
ctx.strokeStyle = "cyan";
for (var i = 0; i < faces.length; i++) {
var item = faces[i].boundingBox;
ctx.strokeStyle = "cyan";
ctx.rect(Math.floor(item.x * scale),
Math.floor(item.y * scale),
Math.floor(item.width * scale),
Math.floor(item.height * scale));
ctx.stroke();
// beautiful green hat
ctx.strokeStyle = "green"
ctx.beginPath();
ctx.moveTo(item.x-10, item.y-10);
ctx.moveTo(item.x+item.width+10, item.y-10);
ctx.bezierCurveTo(item.x+item.width+10, item.y-100, item.x-10, item.y-100, item.x-10, item.y-10);
ctx.fillStyle = "green";
ctx.fill();
ctx.stroke();
}
})
.catch((e) => {
console.error("Face Detection failed: " + e);
});
}
setInterval(function () {
faceDetect();
}, 300);
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment