Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Face Detection using the Shape Detection API
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
<title>Face Detection using the Shape Detection API</title>
<style>
body {
margin: 0;
font-family: sans-serif;
}
.marker {
position: absolute;
border: 2px solid red;
}
button {
display: block;
padding: 15px;
cursor: pointer;
margin-top: 10px;
}
#message {
margin-top: 10px;
}
</style>
</head>
<body>
<img id="image" src="image.jpg" />
<button id="button">Detect faces</button>
<div id="message"></div>
<script>
const image = document.getElementById('image');
const button = document.getElementById('button');
const message = document.getElementById('message');
const addFaceMarker = (boundingBox) => {
const { width, height, top, left } = boundingBox;
const marker = document.createElement('div');
marker.classList.add('marker');
marker.style.width = `${width}px`;
marker.style.height = `${height}px`;
marker.style.top = `${top}px`;
marker.style.left = `${left}px`;
document.body.appendChild(marker);
};
const detectFaces = () => {
if (!window.FaceDetector) {
message.innerText = 'Face Detection is not supported in your browser';
return;
}
const faceDetector = new FaceDetector();
faceDetector
.detect(image)
.then((faces) => {
console.log(faces);
faces.forEach((face) => {
const { boundingBox } = face;
addFaceMarker(boundingBox);
});
message.innerText = `Faces detected: ${faces.length}`;
})
.catch((e) => {
console.error(`Face Detection failed: ${e}`);
});
};
button.addEventListener('click', detectFaces);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment