Skip to content

Instantly share code, notes, and snippets.

@ArunMichaelDsouza
Last active January 31, 2021 00:24
Show Gist options
  • Save ArunMichaelDsouza/b29459609fdd4247a096e9e052ad99dc to your computer and use it in GitHub Desktop.
Save ArunMichaelDsouza/b29459609fdd4247a096e9e052ad99dc to your computer and use it in GitHub Desktop.
Barcode Detection using the Shape Detection API
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
<title>Baracode 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;
}
#message {
margin-top: 10px;
}
.attribution {
font-weight: 300;
font-size: 10px;
text-align: center;
width: 380px;
}
</style>
</head>
<body>
<img id="image" src="barcode.png" />
<div class="attribution">Image source - barcode-list.com</div>
<button id="button">Detect barcode</button>
<div id="message"></div>
<script>
const barcode = document.getElementById('image');
const button = document.getElementById('button');
const message = document.getElementById('message');
const detectBarcode = () => {
if (!window.BarcodeDetector) {
message.innerText =
'Barcode Detection is not supported in your browser';
return;
}
const barcodeDetector = new BarcodeDetector({
formats: ['ean_13'],
});
barcodeDetector
.detect(barcode)
.then((data) => {
console.log(data);
const { rawValue } = data[0];
message.innerText = `Barcode value: ${rawValue}`;
})
.catch((e) => {
console.error(`Barcode Detection failed: ${e}`);
});
};
button.addEventListener('click', detectBarcode);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment