Html5-QRCode
A cross-platform HTML5 QR code reader.
Use this light-weight Javascript library (~68 Kb)
to add QR Code scanning capability in your web application.
- Supports easy scanning using web-cam or camera in the smartphones (Android / IOS).
- Recently Added Scanning QR Code from files or default camera on smartphones.
Support for scanning local files on the device is a new addition and helpful for the web browser which does not support inline web-camera access in smartphones. Note: This doesn't upload files to any server - everything is done locally.
Figure: Running on Android, Pixel 3
Supported platforms
Working on adding support for more and more platforms. If you find a platform or browser where the library is not working please feel free to file an issue. Check the demo link to test out.
Legends
- Means full support - inline webcam and file based
- Means partial support - only file based, webcam in progress
PC / Mac
Firefox | Chrome | Safari | Opera | Edge |
---|
| | | | |
Android
Chrome | Firefox | Edge | Opera | Opera Mini | UC |
---|
| | | | | |
IOS
Apparently, Webkit for IOS is used by Chrome, Firefox, and other browsers in IOS and they do not have webcam permissions yet. There is an ongoing issue on fixing the support for iOS - issue/14
Framework support
The library can be easily used with several other frameworks, I have been adding examples for a few of them and would continue to add more.
This is a cross-platform javascript library to create a QRcode reader for HTML5 compatible browser.
Supports:
- Querying all camera in the device (With user permissions)
- Using any camera for scanning the QR Code.
How to use?
For full information read this article.
Download the script from release page or npm
with:
npm i html5-qrcode
Add an element you want to use as a placeholder for QR Code scanner
<div id="reader" width="600px"></div>
Ideally do not set the height of this container as the height should depend on the height of the video feed from the camera. The library would honor the existing width otherwise apply the default width. The height is derived from the aspect ratio of the video feed.
Add minified/html5-qrcode.min.js
in your web page.
I would recommend using the minified version as it's transformed to standard javascript. The html5-qrcode.js
is written with ECMAScript and may not be supported in the older version of the browsers. I wrote in this as it's easier to maintain!
<script src="./minified/html5-qrcode.js"></script>
Easy Mode - With end to end scanner user interface
Html5QrcodeScanner
lets you implement end to end scanner with few lines of
code with the default user interface which allows scanning using the camera or
selecting an image from the file system.
You can setup the scanner as follows:
function onScanSuccess(qrMessage) {
console.log(`QR matched = ${qrMessage}`);
}
function onScanFailure(error) {
console.warn(`QR error = ${error}`);
}
let html5QrcodeScanner = new Html5QrcodeScanner(
"reader", { fps: 10, qrbox: 250 }, true);
html5QrcodeScanner.render(onScanSuccess, onScanFailure);
Pro Mode - if you want to implement your own user interface
You can use Html5Qrcode
class to set up your QR code scanner (with your own user interface) and allow users to scan QR codes using the camera or by choosing an image file in the file system or native cameras in smartphones.
You can use the following APIs to fetch camera
, start
scanning and stop
scanning.
For using inline QR Code scanning with Webcam or Smartphone camera
Start Scanning
To get a list of supported cameras, query it using static method Html5Qrcode.getCameras()
. This method returns a Promise
with a list of devices supported in format { id: "id", label: "label" }
.
Html5Qrcode.getCameras().then(devices => {
if (devices && devices.length) {
var cameraId = devices[0].id;
}
}).catch(err => {
});
Important: Note that this method will trigger user permission if the user has not granted it already.
Warning: Direct access to the camera is a powerful feature. It requires consent from the user, and your site MUST be on a secure origin (HTTPS).
Warning: Asking for access to the camera on page load will result in most of your users rejecting access to it. More info
Once you have the camera id from device.id
, start camera using Html5Qrcode#start(..)
. This method returns a Promise
with Qr code scanning initiation.
const html5QrCode = new Html5Qrcode( "reader");
html5QrCode.start(
cameraId,
{
fps: 10,
qrbox: 250
},
qrCodeMessage => {
},
errorMessage => {
})
.catch(err => {
});
You can optionally set another argument in constructor called verbose
to print all logs to console
const html5QrCode = new Html5Qrcode("reader", true);
Scanning without cameraId
In mobile devices you may want users to directly scan the QR code using the back camera or the front camera for some use cases. For such cases you can avoid using the exact camera device id that you get from Html5Qrcode.getCameras()
. The start()
method allows passing constraints in place of camera device id similar to html5 web API syntax. You can start scanning like mentioned in these examples:
const html5QrCode = new Html5Qrcode("#reader");
const qrCodeSuccessCallback = message => { }
const config = { fps: 10, qrbox: 250 };
html5QrCode.start({ facingMode: "user" }, config, qrCodeSuccessCallback);
html5QrCode.start({ facingMode: "environment" }, config, qrCodeSuccessCallback);
html5QrCode.start({ facingMode: { exact: "user"} }, config, qrCodeSuccessCallback);
html5QrCode.start({ facingMode: { exact: "environment"} }, config, qrCodeSuccessCallback);
Passing the cameraId
(recommended appraoch) is similar to
html5QrCode.start({ deviceId: { exact: cameraId} }, config, qrCodeSuccessCallback);
Stop Scanning
To stop using camera and thus stop scanning, call Html5Qrcode#stop()
which returns a Promise
for stopping the video feed and scanning.
html5QrCode.stop().then(ignore => {
}).catch(err => {
});
Note that the class is stateful and stop()
should be called to properly tear down the video and camera objects safely after calling start()
when the scan is over or user intend to move on. stop()
will stop the video feed on the viewfinder.
For QR Code scanning using local files or inbuild camera on Smartphones
Selector in Android | Selector in IOS |
---|
Taken on Pixel 3, Google Chrome
| Taken on iPhone 7, Google Chrome
|
You can alternatively leverage QR Code scanning for local files on the device or default camera on the device. It works similar to inline QR Code scanning.
Define the HTML container and import the javascript library as mentioned above
<div id="reader" width="600px" height="600px"></div>
<script src="./minified/html5-qrcode.js"></script>
It's not mandatory to set the height and width of the HTML element. If provided the library would try to honour it. If it's not set the library would set a default width and derive the height based on the input image's aspect ratio.
Add an Input
element for supporting file selection like this:
<input type="file" id="qr-input-file" accept="image/*">
<input type="file" id="qr-input-file" accept="image/*" capture>
Find more information about this at developers.google.com.
And in javascript code initialize the object and attach listener like this:
const html5QrCode = new Html5Qrcode( "reader");
const fileinput = document.getElementById('qr-input-file');
fileinput.addEventListener('change', e => {
if (e.target.files.length == 0) {
return;
}
const imageFile = e.target.files[0];
html5QrCode.scanFile(imageFile, true)
.then(qrCodeMessage => {
console.log(qrCodeMessage);
})
.catch(err => {
console.log(`Error scanning file. Reason: ${err}`)
});
});
Note that inline scanning and file-based scanning are mutually exclusive at the moment. This means, you can only use one of them at a time. I'll soon be adding support for the option to have both if the requirement comes in. If you want to use both, use html5QrCode#clear()
method to clear the canvas.
Demo
Scan this image or visit blog.minhazav.dev/research/html5-qrcode.html
For more information
Check this article on how to use this library, check the following articles:
Screenshots
Figure: Screenshot from Google Chrome running on Macbook Pro
Documentation
Following methods are available in this library
class Html5Qrcode {
static getCameras()
constructor(elementId, verbose ) {}
start(cameraId,
configuration,
qrCodeSuccessCallback,
qrCodeErrorCallback) {}
stop() {}
scanFile(imageFile, showImage) {}
clear() {}
}
class Html5QrcodeScanner {
constructor(elementId, config, verbose) {}
render(qrCodeSuccessCallback, qrCodeErrorCallback) {}
clear() {}
}
This is a configuration for the QR code scanning which can effect both scanning behavior and UI. There are two optional properties right now if you don't want them you can just pass an empty object {}
.
fps
- Integer, Example = 10
A.K.A frame per second, the default value for this is 2 but it can be increased to get faster scanning. Increasing too high value could affect performance. Value >1000
will simply fail.
qrbox
- Integer, Example = 250
Use this property to limit the region of the viewfinder you want to use for scanning. The rest of the viewfinder would be shaded. For example by passing config { qrbox : 250 }
, the screen will look like:
aspectRatio
- Float, Example 1.777778 for 16:9 aspect ratio
Use this property to render the video feed in a certain aspect ratio. Passing a nonstandard aspect ratio like 100000:1
could lead to the video feed not even showing up. Ideal values can be:
Value | Aspect Ratio | Use Case |
---|
1.333334 | 4:3 | Standard camera aspect ratio |
1.777778 | 16:9 | Fullscreen, cinematic |
1.0 | 1:1 | Square view |
If you do not pass any value, the whole viewfinder would be used for scanning.
Note: this value has to be smaller than the width and height of the QR code HTML element
.
disableFlip
- Boolean (Optional), default = false.
By default, the scanner can scan for horizontally flipped QR Codes. This also enables scanning QR code using the front camera on mobile devices which are sometimes mirrored.
This is false
by default and I recommend changing this only if:
- You are sure that the camera feed cannot be mirrored (Horizontally flipped)
- You are facing performance issues with this enabled.
Here's an example of normal and mirrored QR Code
Normal QR Code | Mirrored QR Code |
---|
|
|
How to modify and build
- Code changes should only be made to
- Run
npm run-script build
.
This should do transpiling
--> minification
--> merging
different js code.
- Testing
- Run
npm test
- Run the tests before sending PR, all tests should run.
- Please add tests for new behaviors sent in PR.
- Send a pull request
Credits
The decoder used for the QRcode reading is from LazarSoft
https://github.com/LazarSoft/jsqrcode