Skip to content

JS 条码识别 API 使用教程

Published: at 05:02 PMSuggest Changes

检查是否支持这个 api

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

初始化构造函数

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',
  ],
});

查看支持的条码

async function checkIfFormatIsSupported(format) {
  return await BarcodeDetector.getSupportedFormats().then(
    (supportedFormats) => {
      console.log(supportedFormats);
      return supportedFormats.indexOf(format) !== -1;
    }
  );
}

识别条码

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);
}

Previous Post
在 CentOS 中安装 Puppeteer 依赖项
Next Post
Element 在线运行报错解决