BarcodeDetector:detect() 方法

Limited availability

This feature is not Baseline because it does not work in some of the most widely-used browsers.

安全上下文: 此项功能仅在一些支持的浏览器安全上下文(HTTPS)中可用。

备注: 此特性在 Web Worker 中可用。

实验性: 这是一项实验性技术
在将其用于生产之前,请仔细检查浏览器兼容性表格

BarcodeDetector 接口的 detect() 方法返回一个 Promise,它兑现一个从图像中检测到的条形码的数组

语法

js
detect(imageBitmapSource)

参数

imageBitmapSource

接受一个图像源作为参数;它可以是以下对象之一:HTMLImageElementSVGImageElementHTMLVideoElementHTMLCanvasElementImageBitmapOffscreenCanvasVideoFrameBlob 格式的图像或 ImageData

返回值

返回一个 Promise,它兑现一个具有以下属性的 DetectedBarcode 对象数组:

boundingBox

一个 DOMRectReadOnly,返回表示检测到的条形码范围的矩形尺寸,与图像对齐。

cornerPoints

检测到的条形码的四个角点相对于图像的 x 和 y 坐标,从左上角开始顺时针旋转。由于图像内的透视变形,这可能不是方形的。

format

检测到的条形码格式。(有关格式的完整列表,请参阅受支持的条形码格式类型

rawValue

一个从条形码数据解码的字符串。

异常

TypeError

如果未指定参数或 type 参数不是一个 ImageBitmapSource 类型,抛出此异常。

SecurityError DOMException

如果 imageBitmapSource 有源并且与文档的源不同,或者如果 imageBitmapSource 是一个 HTMLCanvasElement 及其 origin-clean 标志设置为 false,抛出此异常。

InvalidStateError DOMException

如果 imageBitmapSource 是一个 HTMLImageElement 并且未完全解码或解码失败,或者是一个 HTMLVideoElement 并且其 readyState 属性是 HAVE_NOTHINGHAVE_METADATA,抛出此异常。

示例

此示例使用 detect() 方法来检测给定图像中的条形码。识别结果被迭代并且条形码数据被记录到控制台。

js
barcodeDetector
  .detect(imageEl)
  .then((barcodes) => {
    barcodes.forEach((barcode) => console.log(barcode.rawValue));
  })
  .catch((err) => {
    console.error(err);
  });

规范

Specification
Accelerated Shape Detection in Images
# dom-barcodedetector-detect

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
detect
Experimental

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
Partial support
Partial support
No support
No support
Experimental. Expect behavior to change in the future.
See implementation notes.
User must explicitly enable this feature.
Has more compatibility info.