The BarcodeDetector
interface of the Barcode Detection API
allows detection of linear and two dimensional barcodes in images.
This example creates a new barcode detector object, with specified supported formats and tests for browser compatibility.
const barcodeDetector = new BarcodeDetector({
formats: ["code_39", "codabar", "ean_13"],
});
if (barcodeDetector) {
console.log("Barcode Detector supported!");
} else {
console.log("Barcode Detector is not supported by this browser.");
}
The following example calls the getSupportFormat()
static method and logs the results to the console.
BarcodeDetector.getSupportedFormats().then((supportedFormats) => {
supportedFormats.forEach((format) => console.log(format));
});
This example uses the detect()
method to detect the barcodes within the given image. These are iterated over and the barcode data is logged to the console.
barcodeDetector
.detect(imageEl)
.then((barcodes) => {
barcodes.forEach((barcode) => console.log(barcode.rawValue));
})
.catch((err) => {
console.log(err);
});