Chrome ShapeDetetion API BarcodeDetector 适用于 JavaScript,但不适用



我想在 Angular 应用程序中实现 BarcodeDetector。我使用以下代码测试了 API:

.HTML:

<!DOCTYPE html>
<html lang="en">
<head>
<script src="./script.js"></script>
</head>  
<body>
<button onclick="scan()">Click me</button>
<img src="./barcode.gif">
<pre></pre>
</body>
</html>

JavaScript:

function scan() {
const images = document.querySelectorAll('img');
const pres = document.querySelectorAll('pre'); 
try {
pres[0].textContent += 'startedn';
let barcodeDetector = new BarcodeDetector();
pres[0].textContent += 'created and detectingn';
barcodeDetector.detect(images[0]).then(detectedCodes => {
for (const barcode of detectedCodes) {      
pres[0].textContent += barcode.rawValue  + 'n';
}}).catch((e) => {
pres[0].textContent += e + 'n';
});
} catch (e) {
pres[0].textContent += e + 'n';
}
}

它工作得很好。在PC上,当我在手机上打开页面时,我收到NotSupported错误和解码的条形码。

由于TypeScript是JavaScript的超集,我认为移植代码应该非常简单,但显然事实并非如此。角度应用程序中的HTML几乎相同。组件代码如下:

var BarcodeDetector: any;
@Component({
templateUrl: './index.component.html'
})
export class IndexComponent {
@ViewChild('imgRef')
image: ElementRef;
hasBarcodeDetector = '';
errors = '';
scanData = '';
constructor() {
try {
this.hasBarcodeDetector = 'BarcodeDetector' in window ? 'true' : 'false';
const barcodeDetector = new BarcodeDetector();
barcodeDetector.detect(this.image.nativeElement).then(detectedCodes => {
for (const barcode of detectedCodes) {
this.scanData += barcode.rawValue + 'n';
}
});
} catch (e) {
this.errors = e;
}
}
}

检查检测器是否存在有效,因为我得到true,但在 PC 和移动设备上我都收到以下错误:

TypeError: (void 0) is not a constructor

我猜这与解码器的声明有关,但我真的不知道该怎么做。

我认为使用您的变量您会意外覆盖window.BarcodeDetector.另请注意,您没有使用功能检测的结果。顺便说一下,功能检测现在应该以不同的方式发生,如最近更新的文章中所述:

await BarcodeDetector.getSupportedFormats();
/* On a macOS computer logs
[
"aztec",
"code_128",
"code_39",
"code_93",
"data_matrix",
"ean_13",
"ean_8",
"itf",
"pdf417",
"qr_code",
"upc_e"
]
*/

这使您可以检测所需的特定功能,例如 QR 码扫描:

if (('BarcodeDetector' in window) &&
((await BarcodeDetector.getSupportedFormats()).includes('qr_code'))) {
console.log('QR code scanning is supported.');
}

最新更新