BarcodeDetector - 用于检测图像中的线性和二维条形码
BarcodeDetector 是条形码检测 API 的接口,用于检测图像中的线性和二维条形码。
构造函数
BarcodeDetector.BarcodeDetector()
使用可选的 barcodeDetectorOptions 创建并返回一个 BarcodeDetector 对象。
方法
detect()
返回一个 Promise,解析为包含以下属性的 detectedBarcode 对象数组:
boundingBox:一个DOMRectReadOnly,它返回一个矩形的尺寸,该尺寸表示与图像对齐的检测到的条形码的范围。cornerPoints:从左上角开始,顺时针操作,检测到的条形码相对于图像的四个角点的x和y坐标。由于图像内的透视失真,这可能不是正方形。format:检测到的条形码格式。rawValue:从条形码数据中解码得出的String。
getSupportedFormats()
返回一个 Promise,解析为一个 Array,包含支持的条形码格式类型。
实例
创建一个检测器
此实例测试浏览器兼容性,并使用指定的支持格式创建一个新的条形码检测器对象。
// 检查兼容性
if (!('BarcodeDetector' in window)) {
console.log('此浏览器不支持条形码检测器。');
} else {
console.log('支持条形码检测器!');
// 创建新的检测器
var barcodeDetector = new BarcodeDetector({formats: ['code_39', 'codabar', 'ean_13']});
}
获取支持的格式
下面的实例调用 getSupportFormat() 静态方法,并将结果记录到控制台。
// 检查支持的类型
BarcodeDetector.getSupportedFormats()
.then(formats => {
supportedFormats.forEach(format => console.log(format));
});
检测条形码
本实例使用 detect() 方法来检测给定图像内的条形码。重复这些操作,并将条形码数据记录到控制台。
barcodeDetector.detect(imageEl)
.then(barcodes => {
barcodes.forEach(barcode => console.log(barcode.rawData));
})
.catch(err => {
console.log(err);
})
规范
| 规范 | 状态 | 备注 |
|---|---|---|
| Accelerated Shape Detection in Images BarcodeDetector 的定义 |
草稿 | 初始定义。 |
桌面浏览器兼容性
| 特性 | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|---|
| 基础支持 | 83 | 83 | 不支持 | 不支持 | 支持 | 不支持 |
BarcodeDetector() 构造函数 | 83 | 83 | 不支持 | 不支持 | 支持 | 不支持 |
detect | 83 | 83 | 不支持 | 不支持 | 支持 | 不支持 |
getSupportedFormats | 83 | 83 | 不支持 | 不支持 | 支持 | 不支持 |
移动浏览器兼容性
| 特性 | Android | Chrome for Android | Edge mobile | Firefox for Android | IE mobile | Opera Android | iOS Safari |
|---|---|---|---|---|---|---|---|
| 基础支持 | 83 | 83 | 未知 | 不支持 | 未知 | 支持 | 不支持 |
BarcodeDetector() 构造函数 | 83 | 83 | 未知 | 不支持 | 未知 | 支持 | 不支持 |
detect | 83 | 83 | 未知 | 不支持 | 未知 | 支持 | 不支持 |
getSupportedFormats | 83 | 83 | 未知 | 不支持 | 未知 | 支持 | 不支持 |