Skip to content

Instantly share code, notes, and snippets.

@ritwickdey
Last active December 1, 2023 12:27
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ritwickdey/83e56d608d35ce135b975b5947b86ed3 to your computer and use it in GitHub Desktop.
Save ritwickdey/83e56d608d35ce135b975b5947b86ed3 to your computer and use it in GitHub Desktop.
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