BarcodeDetector
注意:此功能在 Web Workers 中可用。
BarcodeDetector 接口(属于 Barcode Detection API)允许在图像中检测线性条形码和二维条形码。
构造函数
BarcodeDetector.BarcodeDetector()实验性-
创建一个并返回一个
BarcodeDetector对象,可以带有可选的BarcodeDetectorOptions。
静态方法
实例方法
detect()实验性-
返回一个
Promise,该 Promise 会 fulfilled 一个包含DetectedBarcode对象的数组,每个对象具有以下属性:boundingBox:一个DOMRectReadOnly对象,表示在图像中检测到的条形码的边界矩形及其尺寸。cornerPoints:检测到的条形码的四个角点的 x 和 y 坐标,相对于图像,从左上角开始顺时针排列。由于图像中的透视失真,这可能不是一个正方形。format:检测到的条形码格式。(有关格式的完整列表,请参阅 支持的条形码格式 列表。)rawValue:从条形码数据解码出的字符串。
示例
创建检测器
此示例创建一个新的条形码检测器对象,指定支持的格式并测试浏览器兼容性。
js
// check compatibility
if (!("BarcodeDetector" in globalThis)) {
console.log("Barcode Detector is not supported by this browser.");
} else {
console.log("Barcode Detector supported!");
// create new detector
const barcodeDetector = new BarcodeDetector({
formats: ["code_39", "codabar", "ean_13"],
});
}
获取支持的格式
以下示例调用 getSupportFormat() 静态方法并将结果记录到控制台。
js
// check supported types
BarcodeDetector.getSupportedFormats().then((supportedFormats) => {
supportedFormats.forEach((format) => console.log(format));
});
检测条形码
此示例使用 detect() 方法检测给定图像中的条形码。然后遍历这些条形码,并将条形码数据记录到控制台。
js
barcodeDetector
.detect(imageEl)
.then((barcodes) => {
barcodes.forEach((barcode) => console.log(barcode.rawValue));
})
.catch((err) => {
console.log(err);
});
规范
| 规范 |
|---|
| 图像中的加速形状检测 # barcode-detection-api |
浏览器兼容性
加载中…