### npm i html5-qrcode
[HTML5SCAN](HTML5 QR Code Scanner Demo | Minhaz’s Blog)
### HTML5 QR Code scanning with javascript - launched v1.0.1 | Minhaz’s Blog
```
// This method will trigger user permissions Html5Qrcode.getCameras().then(devices => { /** * devices would be an array of objects of type: * { id: "id", label: "label" } */ if (devices && devices.length) { var cameraId = devices[0].id; // .. use this to start scanning. } }).catch(err => { // handle err });
// Create instance of the object. The only argument is the "id" of HTML element created above.
const html5QrCode = new Html5Qrcode("reader");
html5QrCode.start(
cameraId, // retreived in the previous step.
{
fps: 10, // sets the framerate to 10 frame per second
qrbox: 250 // sets only 250 X 250 region of viewfinder to
// scannable, rest shaded.
},
qrCodeMessage => {
// do something when code is read. For example:
console.log(`QR Code detected: ${qrCodeMessage}`);
},
errorMessage => {
// parse error, ideally ignore it. For example:
console.log(`QR Code no longer in front of camera.`);
})
.catch(err => {
// Start failed, handle it. For example,
console.log(`Unable to start scanning, error: ${err}`);
});
html5QrCode.stop().then(ignore => {
// QR Code scanning is stopped.
console.log("QR Code scanning stopped.");
}).catch(err => {
// Stop failed, handle it.
console.log("Unable to stop scanning.");
});
html5QrCode.stop().then(ignore => {
// QR Code scanning is stopped.
console.log("QR Code scanning stopped.");
}).catch(err => {
// Stop failed, handle it.
console.log("Unable to stop scanning.");
});
```
·
```tsx
function onScanSuccess(decodedText, decodedResult) { // handle the scanned code as you like, for example: console.log(`Code matched = ${decodedText}`, decodedResult); } let config = { fps: 10, qrbox: {width: 100, height: 100}, rememberLastUsedCamera: true, // Only support camera scan type. supportedScanTypes: [Html5QrcodeScanType.SCAN_TYPE_CAMERA] }; let html5QrcodeScanner = new Html5QrcodeScanner( "reader", config, /* verbose= */ false); html5QrcodeScanner.render(onScanSuccess);
```
<div id="reader"></div>
### 扫描文件
<input type="file" id="qr-input-file" accept="image/*">
```
const html5QrCode = new Html5Qrcode(/* element id */ "reader"); // File based scanning
const fileinput = document.getElementById('qr-input-file');
fileinput.addEventListener('change', e => {
if (e.target.files.length == 0) {
// No file selected, ignore
return;
} // Use the first item in the list
const imageFile = e.target.files[0];
html5QrCode.scanFile(imageFile, /* showImage= */true) .then(qrCodeMessage => {
// success, use qrCodeMessage
console.log(qrCodeMessage);
}) .catch(err => {
// failure, handle it.
console.log(`Error scanning file. Reason: ${err}`) });
});
```
** Clearing the canvas after use**
html5QrCode.clear();