Skip to content

Instantly share code, notes, and snippets.

@ArunMichaelDsouza
Last active January 31, 2021 01:20
Show Gist options
  • Save ArunMichaelDsouza/fc95a5fb574cb2295d2d092aa0c03fbf to your computer and use it in GitHub Desktop.
Save ArunMichaelDsouza/fc95a5fb574cb2295d2d092aa0c03fbf to your computer and use it in GitHub Desktop.
Text Detection using the Shape Detection API
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
<title>Text Detection using the Shape Detection API</title>
<style>
body {
margin: 0 4px;
font-family: sans-serif;
}
button {
display: block;
padding: 15px;
cursor: pointer;
margin-top: 10px;
}
.marker {
position: absolute;
border: 2px solid red;
}
</style>
</head>
<body>
<img id="image" src="text.png" />
<button id="button">Detect text</button>
<script>
const image = document.getElementById('image');
const button = document.getElementById('button');
const message = document.getElementById('message');
const addTextMarker = (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 detectText = () => {
if (!window.TextDetector) {
message.innerText = 'Text Detection is not supported in your browser';
return;
}
const textDetector = new TextDetector();
textDetector
.detect(image)
.then((data) => {
console.log(data);
data.forEach((text) => {
const { boundingBox } = text;
addTextMarker(boundingBox);
});
})
.catch((e) => {
console.error(`Text Detection failed: ${e}`);
});
};
button.addEventListener('click', detectText);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment