Skip to content

Instantly share code, notes, and snippets.

@silphire
Created January 5, 2021 10:15
Show Gist options
  • Save silphire/bf883efe09716906e9ad05261e34a624 to your computer and use it in GitHub Desktop.
Save silphire/bf883efe09716906e9ad05261e34a624 to your computer and use it in GitHub Desktop.
Google Chrome 83以降で正式対応になったBarcode Detection APIのテスト (うまく動かない)
var barcodeDetector = new BarcodeDetector({formats: ['qr_code']});
const bodyElement = document.getElementById('body');
bodyElement.ondragover = (event) => {
event.stopPropagation();
event.preventDefault();
event.dataTransfer.dropEffect = 'copy';
};
bodyElement.ondrop = (event) => {
event.stopPropagation();
event.preventDefault();
if(!('BarcodeDetector' in window)) {
console.log("Barcode Detector not supported");
return;
}
const file = event.dataTransfer.files[0];
new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (event) => {
resolve(event.target.result);
}
reader.readAsDataURL(file);
}).then((result) => {
const image = new Image();
image.src = result;
document.getElementById('barcode').insertAdjacentElement('beforeend', image);
return barcodeDetector.detect(image);
}).then((barcodes) => {
const outputElement = document.getElementById('output');
if(barcodes.length == 0) {
outputElement.insertAdjacentHTML('beforeend', '<li>barcode not decoded</li>');
} else {
barcodes.forEach(barcode => outputElement.insertAdjacentHTML('beforeend', '<li>' + barcode.rawData + '</li>'));
}
});
};
<html>
<head>
<meta charset="utf-8">
<title>Barcode Reader</title>
</head>
<body id="body">
<h1>Barcode Reader</h1>
<p>バーコード画像をドラッグアンドドロップして下さい。</p>
<h1>読み込んだ文字列</h1>
<ul id="output"></ul>
<div id="barcode"></div>
</body>
<script src="barcode.js"></script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment