0%

Js 条码识别 api 使用

检查是否支持这个 api

1
2
3
4
5
if ('BarcodeDetector' in window) {
console.log('Barcode Detector supported!');
} else {
console.log('Barcode Detector is not supported in this browser');
}

初始化构造函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const barcodeDetector = new BarcodeDetector({
formats: [
'aztec',
'code_128',
'code_39',
'code_93',
'codabar',
'data_matrix',
'ean_13',
'ean_8',
'itf',
'pdf417',
'qr_code',
'upc_a',
'upc_e',
],
});

查看支持的条码

1
2
3
4
5
6
7
8
async function checkIfFormatIsSupported(format) {
return await BarcodeDetector.getSupportedFormats().then(
(supportedFormats) => {
console.log(supportedFormats);
return supportedFormats.indexOf(format) !== -1;
}
);
}

识别条码

1
2
3
4
5
6
7
try {
const barcodes = await barcodeDetector.detect(image);
barcodes.forEach((barcode) => console.log(barcode));
} catch (e) {
// if the imageElement is invalid, the DOMException will be thrown
console.error('Barcode detection failed:', e);
}