jsQR
A pure javascript QR code reading library. This library takes in raw images and will locate, extract and parse any QR code found within.
Top Related Projects
ZXing ("Zebra Crossing") barcode scanning library for Java, Android
A cross platform HTML5 QR code reader. See end to end implementation at: https://scanapp.org
Lightweight Javascript QR Code Scanner
HTML5 QR code scanner using your webcam
Quick Overview
jsQR is a pure JavaScript QR code reading library. It's capable of detecting and decoding QR codes directly from raw images, without requiring any external dependencies or native code. This makes it ideal for use in web browsers and Node.js environments.
Pros
- Pure JavaScript implementation, no external dependencies
- Works in both browser and Node.js environments
- Supports reading QR codes from various image formats
- Relatively fast and efficient for a JavaScript-based solution
Cons
- May be slower than native or compiled solutions
- Limited to QR codes only, doesn't support other barcode formats
- Might struggle with low-quality or distorted images compared to more robust solutions
Code Examples
- Basic QR code reading from an image:
import jsQR from "jsqr";
const code = jsQR(imageData, width, height);
if (code) {
console.log("Found QR code", code.data);
}
- Reading QR code from a canvas element:
const canvas = document.getElementById('qr-canvas');
const context = canvas.getContext('2d');
const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
const code = jsQR(imageData.data, imageData.width, imageData.height);
- Using with a video stream for real-time scanning:
function tick() {
if (video.readyState === video.HAVE_ENOUGH_DATA) {
canvasElement.height = video.videoHeight;
canvasElement.width = video.videoWidth;
canvas.drawImage(video, 0, 0, canvasElement.width, canvasElement.height);
var imageData = canvas.getImageData(0, 0, canvasElement.width, canvasElement.height);
var code = jsQR(imageData.data, imageData.width, imageData.height);
if (code) {
console.log("Found QR code", code.data);
}
}
requestAnimationFrame(tick);
}
Getting Started
-
Install the library:
npm install jsqr
-
Import and use in your project:
import jsQR from "jsqr"; // Assuming you have image data in the correct format const code = jsQR(imageData, width, height); if (code) { console.log("Found QR code", code.data); }
-
For browser usage, include the script in your HTML:
<script src="https://cdn.jsdelivr.net/npm/jsqr@1.4.0/dist/jsQR.min.js"></script>
Competitor Comparisons
ZXing ("Zebra Crossing") barcode scanning library for Java, Android
Pros of zxing
- Multi-format support: Handles various barcode formats beyond QR codes
- Mature and widely adopted: Extensive community support and battle-tested in production
- Available in multiple programming languages: Java, C++, and more
Cons of zxing
- Larger codebase and dependencies: May be overkill for simple QR code scanning
- Steeper learning curve: More complex API compared to jsQR
- Potentially slower performance for web-based applications
Code Comparison
jsQR:
const code = jsQR(imageData.data, imageData.width, imageData.height);
if (code) {
console.log("Found QR code", code.data);
}
zxing:
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result = new MultiFormatReader().decode(bitmap);
System.out.println("Found QR code: " + result.getText());
The code examples demonstrate that jsQR offers a simpler API for QR code detection in JavaScript, while zxing requires more setup but provides greater flexibility for various barcode formats in Java.
A cross platform HTML5 QR code reader. See end to end implementation at: https://scanapp.org
Pros of html5-qrcode
- Offers a higher-level API for easier integration into web applications
- Provides built-in support for camera access and real-time scanning
- Includes a user interface component for QR code scanning
Cons of html5-qrcode
- Larger file size and potentially higher resource usage
- May have slower performance for processing individual images
- Less flexibility for custom implementations
Code Comparison
html5-qrcode:
Html5Qrcode.getCameras().then(devices => {
if (devices && devices.length) {
var cameraId = devices[0].id;
const html5QrCode = new Html5Qrcode("reader");
html5QrCode.start(
cameraId,
{
fps: 10,
qrbox: 250
},
qrCodeMessage => {
console.log(`QR Code detected: ${qrCodeMessage}`);
},
errorMessage => {
// parse error, ignore it.
})
.catch(err => {
// Start failed, handle it.
});
}
});
jsQR:
const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');
const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
const code = jsQR(imageData.data, imageData.width, imageData.height);
if (code) {
console.log("Found QR code", code.data);
}
Lightweight Javascript QR Code Scanner
Pros of qr-scanner
- Higher performance due to WebAssembly implementation
- Supports scanning from video streams, enabling real-time QR code detection
- More actively maintained with recent updates and bug fixes
Cons of qr-scanner
- Larger file size due to WebAssembly module
- May have compatibility issues with older browsers that don't support WebAssembly
Code Comparison
qr-scanner:
import QrScanner from 'qr-scanner';
const qrScanner = new QrScanner(
videoElem,
result => console.log('decoded qr code:', result),
{ /* options */ },
);
qrScanner.start();
jsQR:
import jsQR from 'jsqr';
const code = jsQR(imageData.data, imageData.width, imageData.height);
if (code) {
console.log("Found QR code", code.data);
}
Both libraries offer straightforward APIs for QR code scanning, but qr-scanner provides a more streamlined approach for video-based scanning, while jsQR requires manual frame extraction and processing for real-time scanning from video sources.
HTML5 QR code scanner using your webcam
Pros of Instascan
- Real-time scanning capability for live video streams
- Supports multiple cameras and easy camera switching
- Includes a simple UI component for quick integration
Cons of Instascan
- Less actively maintained (last update in 2017)
- Limited to QR codes only, doesn't support other barcode formats
- Requires access to camera, which may not be suitable for all use cases
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);
});
jsQR:
const code = jsQR(imageData.data, imageData.width, imageData.height);
if (code) {
console.log("Found QR code", code.data);
}
jsQR offers a more lightweight approach, working directly with image data without requiring camera access. It's more flexible for various input sources but requires more setup for real-time scanning. Instascan provides an out-of-the-box solution for live video scanning but is limited to QR codes and requires camera access.
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
jsQR
A pure javascript QR code reading library. This library takes in raw images and will locate, extract and parse any QR code found within.
Installation
NPM
Available on npm. Can be used in a Node.js program or with a module bundler such as Webpack or Browserify.
npm install jsqr --save
// ES6 import
import jsQR from "jsqr";
// CommonJS require
const jsQR = require("jsqr");
jsQR(...);
Browser
Alternatively for frontend use jsQR.js
can be included with a script tag
<script src="jsQR.js"></script>
<script>
jsQR(...);
</script>
A note on webcams
jsQR is designed to be a completely standalone library for scanning QR codes. By design it does not include any platform specific code. This allows it to just as easily scan a frontend webcam stream, a user uploaded image, or be used as part of a backend Node.js process.
If you want to use jsQR to scan a webcam stream you'll need to extract the ImageData
from the video stream. This can then be passed to jsQR. The jsQR demo contains a barebones implementation of webcam scanning that can be used as a starting point and customized for your needs. For more advanced questions you can refer to the getUserMedia
docs or the fairly comprehensive webRTC sample code, both of which are great resources for consuming a webcam stream.
Usage
jsQR exports a method that takes in 3 arguments representing the image data you wish to decode. Additionally can take an options object to further configure scanning behavior.
const code = jsQR(imageData, width, height, options?);
if (code) {
console.log("Found QR code", code);
}
Arguments
imageData
- AnUint8ClampedArray
of RGBA pixel values in the form[r0, g0, b0, a0, r1, g1, b1, a1, ...]
. As such the length of this array should be4 * width * height
. This data is in the same form as theImageData
interface, and it's also commonly returned by node modules for reading images.width
- The width of the image you wish to decode.height
- The height of the image you wish to decode.options
(optional) - Additional options.inversionAttempts
- (attemptBoth
(default),dontInvert
,onlyInvert
, orinvertFirst
) - Should jsQR attempt to invert the image to find QR codes with white modules on black backgrounds instead of the black modules on white background. This option defaults toattemptBoth
for backwards compatibility but causes a ~50% performance hit, and will probably be default todontInvert
in future versions.
Return value
If a QR is able to be decoded the library will return an object with the following keys.
binaryData
-Uint8ClampedArray
- The raw bytes of the QR code.data
- The string version of the QR code data.chunks
- The QR chunks.version
- The QR version.location
- An object with keys describing key points of the QR code. Each key is a point of the form{x: number, y: number}
. Has points for the following locations.- Corners -
topRightCorner
/topLeftCorner
/bottomRightCorner
/bottomLeftCorner
; - Finder patterns -
topRightFinderPattern
/topLeftFinderPattern
/bottomLeftFinderPattern
- May also have a point for the
bottomRightAlignmentPattern
assuming one exists and can be located.
- Corners -
Because the library is written in typescript you can also view the type definitions to understand the API.
Contributing
jsQR is written using typescript.
You can view the development source in the src
directory.
Tests can be run with
npm test
Besides unit tests the test suite contains several hundred images that can be found in the /tests/end-to-end/ folder.
Not all the images can be read. In general changes should hope to increase the number of images that read. However due to the nature of computer vision some changes may cause images that pass to start to fail and visa versa. To update the expected outcomes run npm run-script generate-test-data
. These outcomes can be evaluated in the context of a PR to determine if a change improves or harms the overall ability of the library to read QR codes. A summary of which are passing
and failing can be found at /tests/end-to-end/report.json
After testing any changes, you can compile the production version by running
npm run-script build
- Source hosted at GitHub
- Report issues, questions, feature requests on GitHub Issues
Pull requests are welcome! Please create seperate branches for seperate features/patches.
Top Related Projects
ZXing ("Zebra Crossing") barcode scanning library for Java, Android
A cross platform HTML5 QR code reader. See end to end implementation at: https://scanapp.org
Lightweight Javascript QR Code Scanner
HTML5 QR code scanner using your webcam
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