BarcodeDetector
Limited availability
This feature is not Baseline because it does not work in some of the most widely-used browsers.
Secure context: This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.
Note: This feature is available in Web Workers.
Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.
Giao diện BarcodeDetector của Barcode Detection API cho phép phát hiện mã vạch một chiều và hai chiều trong ảnh.
Bộ khởi tạo
BarcodeDetector.BarcodeDetector()Experimental-
Tạo và trả về một đối tượng
BarcodeDetector, vớiBarcodeDetectorOptionslà tùy chọn.
Phương thức tĩnh
getSupportedFormats()Experimental-
Trả về một
Promiseđược hoàn thành với mộtArraygồm các loại định dạng mã vạch được hỗ trợ.
Phương thức thể hiện
detect()Experimental-
Trả về một
Promiseđược hoàn thành với một mảng các đối tượngDetectedBarcodecó các thuộc tính sau:boundingBox: MộtDOMRectReadOnly, trả về kích thước của một hình chữ nhật biểu diễn phạm vi của mã vạch được phát hiện, được căn theo ảnh.cornerPoints: Tọa độ x và y của bốn điểm góc của mã vạch được phát hiện tương đối với ảnh, bắt đầu từ góc trên bên trái và đi theo chiều kim đồng hồ. Hình này có thể không vuông do biến dạng phối cảnh trong ảnh.format: Định dạng mã vạch được phát hiện. (Để xem danh sách đầy đủ các định dạng, hãy tham khảo danh sách định dạng mã vạch được hỗ trợ.)rawValue: Một chuỗi được giải mã từ dữ liệu mã vạch.
Ví dụ
>Tạo một detector
Ví dụ này tạo một đối tượng phát hiện mã vạch mới, với các định dạng được hỗ trợ chỉ định sẵn và kiểm tra tính tương thích của trình duyệt.
// 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"],
});
}
Lấy các định dạng được hỗ trợ
Ví dụ sau gọi phương thức tĩnh getSupportFormat() và ghi kết quả ra bảng điều khiển.
// check supported types
BarcodeDetector.getSupportedFormats().then((supportedFormats) => {
supportedFormats.forEach((format) => console.log(format));
});
Phát hiện mã vạch
Ví dụ này dùng phương thức detect() để phát hiện các mã vạch trong ảnh đã cho. Các mã vạch này sau đó được lặp qua và dữ liệu mã vạch được ghi ra bảng điều khiển.
barcodeDetector
.detect(imageEl)
.then((barcodes) => {
barcodes.forEach((barcode) => console.log(barcode.rawValue));
})
.catch((err) => {
console.log(err);
});
Thông số kỹ thuật
| Specification |
|---|
| Accelerated Shape Detection in Images> # barcode-detection-api> |