Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Face Detection using Google Chrome API (Experimental)
const detectFace = () => {
if(!window.FaceDetector) return console.log('Unsupported Version or Feature is not enabled')
const img = document.querySelector('#targetImg');
const faceDetector = new FaceDetector();
const scale = img.width / img.naturalWidth;
faceDetector
.detect(img)
.then(faces =>
faces.map(face => face.boundingBox)
)
.then(faceBoxes => {
faceBoxes.forEach(faceBox => {
const {
height, width, top, left
} = faceBox;
const div = drawFaceBox(
height, width, top, left, scale
);
img.parentElement.appendChild(div);
});
})
.catch(err => console.log(err));
};
const drawFaceBox = (height, width, top, left, scale) => {
const div = document.createElement('div');
div.className = 'face-box';
div.style.cssText = `
top: ${top * scale}px;
left: ${left * scale}px;
height: ${height * scale}px;
width: ${width * scale}px;
`;
return div;
};
const clearFaceBox = () => {
[...document.getElementsByClassName('face-box')].forEach(e => e.remove());
};
window.onload = () => {
clearFaceBox();
detectFace();
};
window.onresize = () => {
clearFaceBox();
detectFace();
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Face Detection</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<div id="imageContainer" class="images">
<img id="targetImg" class="image" src="<Image URL>" alt="">
</div>
</div>
<script src="face-detection-chrome-api.js"></script>
</body>
</html>
*,
*::after,
*::before {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
overflow-x: hidden;
}
.container {
width: 90%;
margin: auto;
}
#imageContainer {
position: relative;
}
.image {
height: 100%;
width: 100%;
}
.face-box {
position: absolute;
display: inline-block;
min-width: 25px;
min-height: 25px;
border: 3px solid rgb(241, 21, 21);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment