html5-qrcode
A cross platform HTML5 QR code reader. See end to end implementation at: https://scanapp.org
Top Related Projects
Multi-format 1D/2D barcode image processing library, usable in JavaScript ecosystem.
HTML5 QR code scanner using your webcam
Lightweight Javascript QR Code Scanner
A pure javascript QR code reading library. This library takes in raw images and will locate, extract and parse any QR code found within.
Javascript QRCode scanner
Cross-browser QRCode generator for javascript
Quick Overview
html5-qrcode is a lightweight JavaScript library for QR code and barcode scanning using web browsers. It supports scanning from webcam, smartphone cameras, and uploaded images, making it versatile for various web applications.
Pros
- Easy integration with web applications
- Supports multiple input sources (webcam, smartphone camera, file upload)
- No server-side dependencies, runs entirely in the browser
- Customizable UI and extensive configuration options
Cons
- Limited to web-based applications
- Scanning performance may vary depending on device and browser
- Requires HTTPS for camera access in some browsers
- May not work on older browsers that don't support the required Web APIs
Code Examples
- Basic QR code scanning:
const html5QrCode = new Html5Qrcode("reader");
html5QrCode.start(
{ facingMode: "environment" },
{ fps: 10, qrbox: 250 },
(decodedText, decodedResult) => {
console.log(`Code scanned = ${decodedText}`, decodedResult);
},
(errorMessage) => {
// parse error, ignore it.
})
.catch((err) => {
// Start failed, handle it.
});
- Scanning from an image file:
Html5Qrcode.scanFile(imageFile, /* showImage= */true)
.then(decodedText => {
console.log(`Code scanned = ${decodedText}`);
})
.catch(err => {
console.log(`Error scanning file. Reason: ${err}`);
});
- Customizing the scanning area:
const html5QrCode = new Html5Qrcode("reader");
const qrboxFunction = (viewfinderWidth, viewfinderHeight) => {
let minEdgePercentage = 0.7;
let minEdgeSize = Math.min(viewfinderWidth, viewfinderHeight);
let qrboxSize = Math.floor(minEdgeSize * minEdgePercentage);
return {
width: qrboxSize,
height: qrboxSize
};
};
html5QrCode.start({ facingMode: "environment" }, { fps: 10, qrbox: qrboxFunction }, qrCodeSuccessCallback);
Getting Started
-
Include the library in your HTML:
<script src="https://unpkg.com/html5-qrcode" type="text/javascript"></script>
-
Add a container element in your HTML:
<div id="reader"></div>
-
Initialize and start scanning:
const html5QrCode = new Html5Qrcode("reader"); html5QrCode.start( { facingMode: "environment" }, { fps: 10, qrbox: 250 }, (decodedText, decodedResult) => { console.log(`Code scanned = ${decodedText}`, decodedResult); }, (errorMessage) => { // Handle errors } );
Competitor Comparisons
Multi-format 1D/2D barcode image processing library, usable in JavaScript ecosystem.
Pros of zxing-js/library
- Supports a wider range of barcode formats, including 1D and 2D codes
- More mature and well-established project with a larger community
- Provides both browser and Node.js support
Cons of zxing-js/library
- Larger file size and potentially slower performance
- More complex API, which may require a steeper learning curve
- Less focused on QR codes specifically, which may lead to unnecessary overhead for simple QR code scanning
Code Comparison
html5-qrcode:
const html5QrCode = new Html5Qrcode("reader");
html5QrCode.start(
{ facingMode: "environment" },
{ fps: 10, qrbox: 250 },
qrCodeSuccessCallback,
qrCodeErrorCallback
);
zxing-js/library:
const codeReader = new ZXing.BrowserQRCodeReader();
codeReader
.decodeFromVideoDevice(undefined, 'video', (result, err) => {
if (result) console.log(result.text);
if (err) console.error(err);
})
.catch(err => console.error(err));
Both libraries offer straightforward APIs for QR code scanning, but zxing-js/library provides a more generic approach that can be extended to other barcode formats. html5-qrcode focuses specifically on QR codes, resulting in a slightly simpler API for this use case.
HTML5 QR code scanner using your webcam
Pros of Instascan
- Simpler API with fewer configuration options, making it easier to get started quickly
- Supports multiple cameras and camera switching out of the box
- Lightweight and focused solely on QR code scanning
Cons of Instascan
- Less actively maintained, with the last update in 2017
- Limited browser support, mainly works with Chrome and Firefox
- Fewer features and customization options compared to html5-qrcode
Code Comparison
Instascan:
let scanner = new Instascan.Scanner({ video: document.getElementById('preview') });
scanner.addListener('scan', function (content) {
console.log(content);
});
Instascan.Camera.getCameras().then(function (cameras) {
if (cameras.length > 0) {
scanner.start(cameras[0]);
}
}).catch(function (e) {
console.error(e);
});
html5-qrcode:
let html5QrcodeScanner = new Html5QrcodeScanner(
"reader", { fps: 10, qrbox: 250 });
html5QrcodeScanner.render(onScanSuccess, onScanError);
function onScanSuccess(decodedText, decodedResult) {
console.log(`Code scanned = ${decodedText}`, decodedResult);
}
function onScanError(errorMessage) {
// handle scan error
}
Both libraries offer straightforward ways to implement QR code scanning, but html5-qrcode provides more configuration options and broader browser support. Instascan's simplicity may be preferable for basic use cases, while html5-qrcode offers more flexibility for complex implementations.
Lightweight Javascript QR Code Scanner
Pros of qr-scanner
- Smaller bundle size, making it more lightweight for web applications
- Supports scanning QR codes from image files in addition to camera input
- Offers a simpler API, potentially easier for beginners to implement
Cons of qr-scanner
- Less comprehensive documentation compared to html5-qrcode
- Fewer configuration options for advanced use cases
- Limited support for older browsers and devices
Code Comparison
html5-qrcode:
const html5QrCode = new Html5Qrcode("reader");
html5QrCode.start(
{ facingMode: "environment" },
{ fps: 10, qrbox: 250 },
qrCodeSuccessCallback,
qrCodeErrorCallback
);
qr-scanner:
const qrScanner = new QrScanner(
videoElem,
result => console.log('decoded qr code:', result),
{ /* options */ }
);
qrScanner.start();
Both libraries offer straightforward implementation, but qr-scanner's API is slightly more concise. html5-qrcode provides more granular control over scanning parameters, while qr-scanner opts for a simpler approach with fewer configuration options.
A pure javascript QR code reading library. This library takes in raw images and will locate, extract and parse any QR code found within.
Pros of jsQR
- Pure JavaScript implementation, no external dependencies
- Lightweight and easy to integrate into web projects
- Supports a wide range of QR code versions and error correction levels
Cons of jsQR
- Limited to QR code scanning only, doesn't support other barcode formats
- Lacks built-in camera handling and user interface components
- May require additional code for real-time scanning from video streams
Code Comparison
html5-qrcode:
const html5QrCode = new Html5Qrcode("reader");
html5QrCode.start(
{ facingMode: "environment" },
{ fps: 10, qrbox: 250 },
qrCodeSuccessCallback,
qrCodeErrorCallback
);
jsQR:
const code = jsQR(imageData.data, imageData.width, imageData.height);
if (code) {
console.log("Found QR code", code.data);
}
html5-qrcode provides a higher-level API with built-in camera handling and scanning options, while jsQR requires more manual setup but offers lower-level control over the scanning process. html5-qrcode is more suitable for quick integration in web applications, whereas jsQR might be preferred for custom implementations or when fine-grained control is needed.
Javascript QRCode scanner
Pros of jsqrcode
- Lightweight and focused solely on QR code decoding
- Supports a wide range of QR code versions and error correction levels
- Can be easily integrated into existing projects without additional dependencies
Cons of jsqrcode
- Less actively maintained, with fewer recent updates
- Limited built-in features for camera handling and real-time scanning
- Requires more manual setup for use in web applications
Code Comparison
jsqrcode:
qrcode.decode(imageData);
qrcode.callback = function(result) {
console.log(result);
};
html5-qrcode:
const html5QrCode = new Html5Qrcode("reader");
html5QrCode.start(
{ facingMode: "environment" },
{ fps: 10, qrbox: 250 },
(decodedText, decodedResult) => {
console.log(`Code scanned = ${decodedText}`, decodedResult);
},
(errorMessage) => {
// parse error, ignore it.
})
.catch((err) => {
// Start failed, handle it.
});
The html5-qrcode library provides a more comprehensive solution with built-in camera handling and real-time scanning capabilities, while jsqrcode focuses on core QR code decoding functionality, requiring additional setup for camera integration.
Cross-browser QRCode generator for javascript
Pros of qrcodejs
- Lightweight and simple to use for generating QR codes
- No external dependencies required
- Supports various output formats (canvas, table, SVG)
Cons of qrcodejs
- Limited to QR code generation only, no scanning capabilities
- Less actively maintained compared to html5-qrcode
- Fewer customization options for QR code appearance
Code Comparison
html5-qrcode (scanning):
const html5QrCode = new Html5Qrcode("reader");
html5QrCode.start(
{ facingMode: "environment" },
{ fps: 10, qrbox: 250 },
qrCodeSuccessCallback,
qrCodeErrorCallback
);
qrcodejs (generation):
const qrcode = new QRCode("qrcode", {
text: "https://example.com",
width: 128,
height: 128,
colorDark: "#000000",
colorLight: "#ffffff",
});
The code examples highlight the different focus areas of the two libraries. html5-qrcode provides a more comprehensive API for QR code scanning with various configuration options, while qrcodejs offers a straightforward approach to QR code generation with basic customization.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Html5-QRCode
Important - Looking for new owners for this project.
If interested, please reach out at minhazav@gmail.com
.
Html5-QRCode
Important The project is in maintenance mode until further notice. The author shall not be able to make any bug fixes or improvements for the time-being. Pull requests also won't be merged for the timebeing. If you have a fork you can maintain - please share the details to minhazav@gmail.com. I am happy to advertise them here! Ok to use the project as is. Example: scanapp.org.
Lightweight & cross platform QR Code and Bar code scanning library for the web
Use this lightweight library to easily / quickly integrate QR code, bar code, and other common code scanning capabilities to your web application.
Key highlights
-
ð² Support scanning different types of bar codes and QR codes.
-
ð¥ Supports different platforms be it Android, IOS, MacOs, Windows or Linux
-
ð Supports different browsers like Chrome, Firefox, Safari, Edge, Opera ...
-
ð· Supports scanning with camera as well as local files
-
â¡ï¸ Comes with an end to end library with UI as well as a low level library to build your own UI with.
-
ð¦ Supports customisations like flash/torch support, zooming etc.
Supports two kinds of APIs
-
Html5QrcodeScanner
â End-to-end scanner with UI, integrate with less than ten lines of code. -
Html5Qrcode
â Powerful set of APIs you can use to build your UI without worrying about camera setup, handling permissions, reading codes, etc.
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.
Demo at scanapp.org | Demo at qrcode.minhazav.dev - Scanning different types of codes |
We need your help!
Help incentivise feature development, bug fixing by supporting the sponsorhip goals of this project. See list of sponsered feature requests here.
Documentation
The documentation for this project has been moved to scanapp.org/html5-qrcode-docs.
Supported platforms
We are working continuously on adding support for more and more platforms. If you find a platform or a browser where the library is not working, please feel free to file an issue. Check the demo link to test it 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
Safari | Chrome | Firefox | Edge |
---|---|---|---|
* | * |
* Supported for IOS versions >= 15.1
Before version 15.1, 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.
Html5 | VueJs | ElectronJs | React | Lit |
Supported Code formats
Code scanning is dependent on Zxing-js library. We will be working on top of it to add support for more types of code scanning. If you feel a certain type of code would be helpful to have, please file a feature request.
Code | Example |
---|---|
QR Code | |
AZTEC | |
CODE_39 | |
CODE_93 | |
CODE_128 | |
ITF | |
EAN_13 | |
EAN_8 | |
PDF_417 | |
UPC_A | |
UPC_E | |
DATA_MATRIX | |
MAXICODE* | |
RSS_14* | |
RSS_EXPANDED* |
*Formats are not supported by our experimental integration with native BarcodeDetector API integration (Read more).
Description - View Demo
See an end to end scanner experience at scanapp.org.
This is a cross-platform JavaScript library to integrate QR code, bar codes & a few other types of code scanning capabilities to your applications running on HTML5 compatible browser.
Supports:
- Querying camera on the device (with user permissions)
- Rendering live camera feed, with easy to use user interface for scanning
- Supports scanning a different kind of QR codes, bar codes and other formats
- Supports selecting image files from the device for scanning codes
How to use
Find detailed guidelines on how to use this library on scanapp.org/html5-qrcode-docs.
Demo
Scan this image or visit blog.minhazav.dev/research/html5-qrcode.html
For more information
Check these articles on how to use this library:
- QR and barcode scanner using HTML and JavaScript
- HTML5 QR Code scanning â launched v1.0.1 without jQuery dependency and refactored Promise based APIs.
- HTML5 QR Code scanning with JavaScript â Support for scanning the local file and using default camera added (v1.0.5)
Screenshots
Figure: Screenshot from Google Chrome running on MacBook Pro
Documentation
Find the full API documentation at scanapp.org/html5-qrcode-docs/docs/apis.
Extra optional configuration
in start()
method
Configuration object that can be used to configure both the scanning behavior and the user interface (UI). Most of the fields have default properties that will be used unless a different value is provided. If you do not want to override anything, you can just pass in 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
â QrDimensions
or QrDimensionFunction
(Optional), Example = { width: 250, height: 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 : { width: 250, height: 250 } }
, the screen will look like:
This can be used to set a rectangular scanning area with config like:
let config = { qrbox : { width: 400, height: 150 } }
This config also accepts a function of type
/**
* A function that takes in the width and height of the video stream
* and returns QrDimensions.
*
* Viewfinder refers to the video showing camera stream.
*/
type QrDimensionFunction =
(viewfinderWidth: number, viewfinderHeight: number) => QrDimensions;
This allows you to set dynamic QR box dimensions based on the video dimensions. See this blog article for example: Setting dynamic QR box size in Html5-qrcode - ScanApp blog
This might be desirable for bar code scanning.
If this value is not set, no shaded QR box will be rendered and the scanner will scan the entire area of video stream.
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 | Full screen, 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 a normal and mirrored QR Code
Normal QR Code | Mirrored QR Code |
---|---|
rememberLastUsedCamera
â Boolean (Optional), default = true
If true
the last camera used by the user and weather or not permission was granted would be remembered in the local storage. If the user has previously granted permissions â the request permission option in the UI will be skipped and the last selected camera would be launched automatically for scanning.
If true
the library shall remember if the camera permissions were previously
granted and what camera was last used. If the permissions is already granted for
"camera", QR code scanning will automatically * start for previously used camera.
supportedScanTypes
- Array<Html5QrcodeScanType> | []
This is only supported for
Html5QrcodeScanner
.
Default = [Html5QrcodeScanType.SCAN_TYPE_CAMERA, Html5QrcodeScanType.SCAN_TYPE_FILE]
This field can be used to:
- Limit support to either of
Camera
orFile
based scan. - Change default scan type.
How to use:
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);
For file based scan only choose:
supportedScanTypes: [Html5QrcodeScanType.SCAN_TYPE_FILE]
For supporting both as it is today, you can ignore this field or set as:
supportedScanTypes: [
Html5QrcodeScanType.SCAN_TYPE_CAMERA,
Html5QrcodeScanType.SCAN_TYPE_FILE]
To set the file based scan as defult change the order:
supportedScanTypes: [
Html5QrcodeScanType.SCAN_TYPE_FILE,
Html5QrcodeScanType.SCAN_TYPE_CAMERA]
showTorchButtonIfSupported
- boolean | undefined
This is only supported for
Html5QrcodeScanner
.
If true
the rendered UI will have button to turn flash on or off based on device + browser support. The value is false
by default.
Scanning only specific formats
By default, both camera stream and image files are scanned against all the
supported code formats. Both Html5QrcodeScanner
and Html5Qrcode
classes can
be configured to only support a subset of supported formats. Supported formats
are defined in
enum Html5QrcodeSupportedFormats.
enum Html5QrcodeSupportedFormats {
QR_CODE = 0,
AZTEC,
CODABAR,
CODE_39,
CODE_93,
CODE_128,
DATA_MATRIX,
MAXICODE,
ITF,
EAN_13,
EAN_8,
PDF_417,
RSS_14,
RSS_EXPANDED,
UPC_A,
UPC_E,
UPC_EAN_EXTENSION,
}
I recommend using this only if you need to explicitly omit support for certain formats or want to reduce the number of scans done per second for performance reasons.
Scanning only QR code with Html5Qrcode
const html5QrCode = new Html5Qrcode(
"reader", { formatsToSupport: [ Html5QrcodeSupportedFormats.QR_CODE ] });
const qrCodeSuccessCallback = (decodedText, decodedResult) => {
/* handle success */
};
const config = { fps: 10, qrbox: { width: 250, height: 250 } };
// If you want to prefer front camera
html5QrCode.start({ facingMode: "user" }, config, qrCodeSuccessCallback);
Scanning only QR code and UPC codes with Html5QrcodeScanner
function onScanSuccess(decodedText, decodedResult) {
// Handle the scanned code as you like, for example:
console.log(`Code matched = ${decodedText}`, decodedResult);
}
const formatsToSupport = [
Html5QrcodeSupportedFormats.QR_CODE,
Html5QrcodeSupportedFormats.UPC_A,
Html5QrcodeSupportedFormats.UPC_E,
Html5QrcodeSupportedFormats.UPC_EAN_EXTENSION,
];
const html5QrcodeScanner = new Html5QrcodeScanner(
"reader",
{
fps: 10,
qrbox: { width: 250, height: 250 },
formatsToSupport: formatsToSupport
},
/* verbose= */ false);
html5QrcodeScanner.render(onScanSuccess);
Experimental features
The library now supports some experimental features which are supported in the library but not recommended for production usage either due to limited testing done or limited compatibility for underlying APIs used. Read more about it here. Some experimental features include:
How to modify and build
-
Code changes should only be made to /src only.
-
Run
npm install
to install all dependencies. -
Run
npm run-script build
to build JavaScript output. The output JavaScript distribution is built to /dist/html5-qrcode.min.js. If you are developing on Windows OS, runnpm run-script build-windows
. -
Testing
- Run
npm test
- Run the tests before sending a pull request, all tests should run.
- Please add tests for new behaviors sent in PR.
- Run
-
Send a pull request
- Include code changes only to
./src
. Do not change./dist
manually. - In the pull request add a comment like
@all-contributors please add @mebjas for this new feature or tests
- For calling out your contributions, the bot will update the contributions file.
- Code will be built & published by the author in batches.
- Include code changes only to
How to contribute
You can contribute to the project in several ways:
- File issue ticket for any observed bug or compatibility issue with the project.
- File feature request for missing features.
- Take open bugs or feature request and work on it and send a Pull Request.
- Write unit tests for existing codebase (which is not covered by tests today). Help wanted on this - read more.
Support ð
This project would not be possible without all of our fantastic contributors and sponsors. If you'd like to support the maintenance and upkeep of this project you can donate via GitHub Sponsors.
Sponsor the project for priortising feature requests / bugs relevant to you. (Depends on scope of ask and bandwidth of the contributors).
Help incentivise feature development, bug fixing by supporting the sponsorhip goals of this project. See list of sponsered feature requests here.
Also, huge thanks to following organizations for non monitery sponsorships
Credits
The decoder used for the QR code reading is from Zxing-js
https://github.com/zxing-js/library
Top Related Projects
Multi-format 1D/2D barcode image processing library, usable in JavaScript ecosystem.
HTML5 QR code scanner using your webcam
Lightweight Javascript QR Code Scanner
A pure javascript QR code reading library. This library takes in raw images and will locate, extract and parse any QR code found within.
Javascript QRCode scanner
Cross-browser QRCode generator for javascript
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot