Convert Figma logo to code with AI

nimiq logoqr-scanner

Lightweight Javascript QR Code Scanner

2,464
533
2,464
112

Top Related Projects

32,747

ZXing ("Zebra Crossing") barcode scanning library for Java, Android

3,701

A pure javascript QR code reading library. This library takes in raw images and will locate, extract and parse any QR code found within.

A cross platform HTML5 QR code reader. See end to end implementation at: https://scanapp.org

HTML5 QR code scanner using your webcam

Javascript QRCode scanner

13,583

Cross-browser QRCode generator for javascript

Quick Overview

Nimiq/qr-scanner is a lightweight and efficient JavaScript QR code scanner library. It's designed to work in browsers, utilizing the device's camera to scan QR codes in real-time. The library is built with performance and ease of use in mind, making it suitable for various web applications.

Pros

  • Fast and efficient QR code scanning
  • Works in browsers without additional dependencies
  • Supports both front and back cameras on mobile devices
  • Lightweight and easy to integrate into existing projects

Cons

  • Limited to QR code scanning (doesn't support other barcode formats)
  • Requires HTTPS for camera access in most browsers
  • May have compatibility issues with older browsers
  • Depends on browser support for getUserMedia API

Code Examples

  1. Basic QR code scanning:
import QrScanner from 'qr-scanner';

const videoElem = document.getElementById('qr-video');
const qrScanner = new QrScanner(videoElem, result => console.log('QR code detected:', result));
qrScanner.start();
  1. Scanning an image file:
import QrScanner from 'qr-scanner';

const fileInput = document.getElementById('file-input');
fileInput.addEventListener('change', async (e) => {
    const file = e.target.files[0];
    const result = await QrScanner.scanImage(file);
    console.log('QR code result:', result);
});
  1. Using a specific camera:
import QrScanner from 'qr-scanner';

const videoElem = document.getElementById('qr-video');
const qrScanner = new QrScanner(videoElem, result => console.log('QR code detected:', result));

QrScanner.listCameras().then(cameras => {
    const backCamera = cameras.find(camera => camera.label.toLowerCase().includes('back'));
    if (backCamera) {
        qrScanner.setCamera(backCamera.id);
    }
    qrScanner.start();
});

Getting Started

  1. Install the library:

    npm install qr-scanner
    
  2. Import and use in your project:

    import QrScanner from 'qr-scanner';
    
    const videoElem = document.getElementById('qr-video');
    const qrScanner = new QrScanner(videoElem, result => {
        console.log('QR code detected:', result);
        qrScanner.stop();
    });
    
    qrScanner.start();
    
  3. Make sure to include a video element in your HTML:

    <video id="qr-video"></video>
    

Remember to serve your application over HTTPS to ensure camera access in most browsers.

Competitor Comparisons

32,747

ZXing ("Zebra Crossing") barcode scanning library for Java, Android

Pros of zxing

  • More comprehensive barcode support, including 1D and 2D formats
  • Mature and widely adopted library with extensive documentation
  • Available in multiple programming languages (Java, C++, etc.)

Cons of zxing

  • Larger library size, which may impact performance in web applications
  • More complex setup and integration process
  • May require additional dependencies for certain functionalities

Code Comparison

zxing (Java):

MultiFormatReader reader = new MultiFormatReader();
Result result = reader.decode(binaryBitmap);
String decodedText = result.getText();

qr-scanner (JavaScript):

const qrScanner = new QrScanner(videoElem, result => console.log(result));
await qrScanner.start();

Summary

zxing offers a more comprehensive barcode scanning solution with support for multiple formats and languages. However, it may be overkill for simple QR code scanning tasks, where qr-scanner provides a lightweight and easy-to-use alternative specifically designed for web applications. qr-scanner's simplicity and focus on QR codes make it a better choice for projects that don't require extensive barcode support or cross-platform compatibility.

3,701

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 dependencies required
  • Works in both browser and Node.js environments
  • Supports a wider range of QR code versions and error correction levels

Cons of jsQR

  • Generally slower performance compared to qr-scanner
  • Less actively maintained (last update was over 3 years ago)
  • Lacks built-in camera support for browser environments

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);
}

The main difference in usage is that qr-scanner provides a higher-level API with built-in video handling, while jsQR requires manual frame extraction and processing. qr-scanner is more suited for quick implementation in web applications, whereas jsQR offers more flexibility for custom implementations across different platforms.

A cross platform HTML5 QR code reader. See end to end implementation at: https://scanapp.org

Pros of html5-qrcode

  • More comprehensive API with additional features like file-based scanning
  • Better documentation and examples for various use cases
  • Supports both 1D and 2D barcode formats

Cons of html5-qrcode

  • Larger file size, which may impact load times
  • More complex setup process compared to qr-scanner
  • May have higher CPU usage due to additional features

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),
  { returnDetailedScanResult: true }
);
qrScanner.start();

Both libraries offer easy-to-use APIs for QR code scanning, but html5-qrcode provides more options and flexibility at the cost of simplicity. qr-scanner focuses on a streamlined approach with a smaller footprint, making it ideal for projects with simpler requirements. The choice between the two depends on the specific needs of your project, balancing features against performance and ease of implementation.

HTML5 QR code scanner using your webcam

Pros of Instascan

  • Simpler API with fewer configuration options, making it easier to use for basic scanning needs
  • Built-in support for multiple cameras and camera switching
  • Includes a pre-built UI component for quick integration

Cons of Instascan

  • Less actively maintained, with the last update in 2018
  • Limited browser support, primarily focused on Chrome
  • Lacks advanced features like worker threads for improved performance

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]);
  }
});

QR Scanner:

const qrScanner = new QrScanner(videoElem, result => console.log('decoded qr code:', result));
qrScanner.start();

QR Scanner offers a more concise API for basic usage, while Instascan provides built-in camera handling. QR Scanner's approach allows for easier integration with custom UIs and more flexibility in handling scanning results. However, Instascan's pre-built components can be advantageous for rapid prototyping or simple applications.

Javascript QRCode scanner

Pros of jsqrcode

  • More established project with longer history and wider adoption
  • Supports a broader range of QR code versions and error correction levels
  • Provides more granular control over decoding process

Cons of jsqrcode

  • Larger file size and potentially slower performance
  • Less actively maintained, with fewer recent updates
  • More complex API, requiring more setup and configuration

Code Comparison

jsqrcode:

qrcode.callback = function(result) {
    if(result instanceof Error) {
        console.log("Error: " + result.message);
    } else {
        console.log("QR Code result: " + result);
    }
};
qrcode.decode(imageData);

qr-scanner:

const qrScanner = new QrScanner(videoElem, result => console.log('QR Code result:', result));
await qrScanner.start();

Summary

jsqrcode offers more comprehensive QR code support and flexibility, making it suitable for complex use cases. However, qr-scanner provides a more modern, streamlined API with better performance and active maintenance. qr-scanner is ideal for simpler implementations and projects requiring frequent updates, while jsqrcode may be preferable for applications needing extensive QR code capabilities or fine-tuned control over the decoding process.

13,583

Cross-browser QRCode generator for javascript

Pros of qrcodejs

  • Lightweight and easy to use, with no dependencies
  • Supports generating QR codes in various formats (canvas, table, SVG)
  • Works well in both browser and Node.js environments

Cons of qrcodejs

  • Limited to QR code generation only, cannot scan QR codes
  • Less actively maintained, with fewer recent updates
  • Lacks advanced features like error correction level adjustment

Code Comparison

qrcodejs (QR code generation):

var qrcode = new QRCode("qrcode", {
    text: "https://example.com",
    width: 128,
    height: 128,
    colorDark : "#000000",
    colorLight : "#ffffff",
    correctLevel : QRCode.CorrectLevel.H
});

qr-scanner (QR code scanning):

const qrScanner = new QrScanner(
    videoElem,
    result => console.log('decoded qr code:', result),
    { /* options */ }
);
qrScanner.start();

Key Differences

  • qrcodejs focuses on QR code generation, while qr-scanner specializes in QR code scanning
  • qr-scanner is more actively maintained and offers a wider range of features for QR code detection
  • qrcodejs is simpler to set up for basic QR code generation tasks, while qr-scanner provides more advanced scanning capabilities

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

QR Scanner

Javascript QR Code Scanner based on Cosmo Wolfe's javascript port of Google's ZXing library.

In this library, several improvements have been applied over the original port:

  • Web cam scanning support out of the box
  • Uses the browser's native BarcodeDetector if available
  • Lightweight: ~59.3 kB (~16.3 kB gzipped) minified with Google's closure compiler. If the native BarcodeDetector is available, only ~15.3 kB (~5.6 kB gzipped) are loaded.
  • Improved performance and reduced memory footprint.
  • Runs in a WebWorker which keeps the main / UI thread responsive.
  • Can be configured for better performance on colored QR codes.

According to our benchmarking this project's scanner engine's detection rate is about 2-3 times (and up to 8 times) as high as the one of the most popular javascript QR scanner library LazarSoft/jsqrcode. Also the other library oftentimes misreads the content of QR codes, while for this project no misreads occurred in the benchmarking.

The library supports scanning a continuous video stream from a web cam as well as scanning of single images.

The development of this library is sponsored by nimiq, world's first browser based blockchain.

nimiq.com

Demo

See https://nimiq.github.io/qr-scanner/demo/

Installation

To install via npm:

npm install --save qr-scanner

To install via yarn:

yarn add qr-scanner

Or simply copy qr-scanner.min.js and qr-scanner-worker.min.js to your project.

Setup

The QR Scanner consists of two main files. qr-scanner.min.js is the main API file which loads the worker script qr-scanner-worker.min.js via a dynamic import, only if needed. If you are not using a bundler like Rollup or Webpack that handles dynamic imports automatically, you might have to copy qr-scanner-worker.min.js over to your dist, next to qr-scanner.min.js or next to the script into which you're bundling qr-scanner.min.js.

qr-scanner.min.js is an es6 module and can be imported as follows:

import QrScanner from 'path/to/qr-scanner.min.js'; // if using plain es6 import
import QrScanner from 'qr-scanner'; // if installed via package and bundling with a module bundler like webpack or rollup

This requires the importing script to also be an es6 module or a module script tag, e.g.:

<script type="module">
    import QrScanner from 'path/to/qr-scanner.min.js';
    // do something with QrScanner
</script>

If your project is not based on es6 modules you can

import('path/to/qr-scanner.min.js').then((module) => {
    const QrScanner = module.default;
    // do something with QrScanner
});
  • use the UMD build qr-scanner.umd.min.js for direct usage as non-module script
<script src="path/to/qr-scanner.umd.min.js"></script>
<script>
    // do something with QrScanner
</script>
  • bundle qr-scanner.umd.min.js directly with your non-module code with tools like gulp or grunt.
  • bundle the lib with require based bundlers like browserify:
const QrScanner = require('qr-scanner'); // if installed via package
const QrScanner = require('path/to/qr-scanner.umd.min.js'); // if not installed via package
// do something with QrScanner

This library uses ECMAScript 2017 features like async functions. If you need to support old browsers, you can use qr-scanner.legacy.min.js, which is ECMAScript 2015 (ES6) compatible. It's a UMD build and can be used as a replacement for qr-scanner.umd.min.js, see above. Note, that the legacy build is larger as it includes some polyfills and, to support browsers that don't support dynamic imports, inlines the worker script which however would be needed to be loaded in legacy browsers anyway. You will likely not need to use the legacy build though, as general browser support is already very good for the regular build. Especially if you want to scan from the device's camera, camera support by the browser is the stricter restriction.

Usage

Web Cam Scanning

1. Create HTML

Create a <video> element where the web cam video stream should get rendered:

<video></video>

2. Create a QrScanner Instance

// To enforce the use of the new api with detailed scan results, call the constructor with an options object, see below.
const qrScanner = new QrScanner(
    videoElem,
    result => console.log('decoded qr code:', result),
    { /* your options or returnDetailedScanResult: true if you're not specifying any other options */ },
);

// For backwards compatibility, omitting the options object will currently use the old api, returning scan results as
// simple strings. This old api will be removed in the next major release, by which point the options object is then
// also not required anymore to enable the new api.
const qrScanner = new QrScanner(
    videoElem,
    result => console.log('decoded qr code:', result),
    // No options provided. This will use the old api and is deprecated in the current version until next major version.
);

As an optional third parameter an options object can be provided. Supported options are:

OptionDescription
onDecodeErrorHandler to be invoked on decoding errors. The default is QrScanner._onDecodeError.
preferredCameraPreference for the camera to be used. The preference can be either a device id as returned by listCameras or a facing mode specified as 'environment' or 'user'. The default is 'environment'. Note that there is no guarantee that the preference can actually be fulfilled.
maxScansPerSecondThis option can be used to throttle the scans for less battery consumption. The default is 25. If supported by the browser, the scan rate is never higher than the camera's frame rate to avoid unnecessary duplicate scans on the same frame.
calculateScanRegionA method that determines a region to which scanning should be restricted as a performance improvement. This region can optionally also be scaled down before performing the scan as an additional performance improvement. The region is specified as x, y, width and height; the dimensions for the downscaled region as downScaledWidth and downScaledHeight. Note that the aspect ratio between width and height and downScaledWidth and downScaledHeight should remain the same. By default, the scan region is restricted to a centered square of two thirds of the video width or height, whichever is smaller, and scaled down to a 400x400 square.
highlightScanRegionSet this option to true for rendering an outline around the scan region on the video stream. This uses an absolutely positioned div that covers the scan region. This div can either be supplied as option overlay, see below, or automatically created and then accessed via qrScanner.$overlay. It can be freely styled via CSS, e.g. by setting an outline, border, background color, etc. See the demo for examples.
highlightCodeOutlineSet this option to true for rendering an outline around detected QR codes. This uses an absolutely positioned div on which an SVG for rendering the outline will be placed. This div can either be supplied as option overlay, see below, or be accessed via qrScanner.$overlay. The SVG can be freely styled via CSS, e.g. by setting the fill color, stroke color, stroke width, etc. See the demo for examples. For more special needs, you can also use the cornerPoints directly, see below, for rendering an outline or the points yourself.
overlayA custom div that can be supplied for use for highlightScanRegion and highlightCodeOutline. The div should be a sibling of videoElem in the DOM. If this option is supplied, the default styles for highlightCodeOutline are not applied as the expectation is that the element already has some custom style applied to it.
returnDetailedScanResultEnforce reporting detailed scan results, see below.

To use the default value for an option, omit it or supply undefined.

Results passed to the callback depend on whether an options object was provided:

  • If no options object was provided, the result is a string with the read QR code's content. The simple string return type is for backwards compatibility, is now deprecated and will be removed in the future.
  • If an options object was provided the result is an object with properties data which is the read QR code's string content and cornerPoints which are the corner points of the read QR code's outline on the camera stream.

To avoid usage of the deprecated api if you're not supplying any other options, you can supply { returnDetailedScanResult: true } to enable the new api and get the detailed scan result.

3. Start scanning

qrScanner.start();

Call it when you're ready to scan, for example on a button click or directly on page load. It will prompt the user for permission to use a camera. Note: to read from a Web Cam stream, your page must be served via HTTPS.

4. Stop scanning

qrScanner.stop();

If you want, you can stop scanning anytime and resume it by calling start() again.

Single Image Scanning

QrScanner.scanImage(image)
    .then(result => console.log(result))
    .catch(error => console.log(error || 'No QR code found.'));

Supported image sources are: HTMLImageElement, SVGImageElement, HTMLVideoElement, HTMLCanvasElement, ImageBitmap, OffscreenCanvas, File / Blob, Data URIs, URLs pointing to an image (if they are on the same origin or CORS enabled)

As an optional second parameter an options object can be provided. Supported options are:

OptionDescription
scanRegionA region defined by x, y, width and height to which the search for a QR code should be restricted. As a performance improvement this region can be scaled down before performing the scan by providing a downScaledWidth and downScaledHeight. Note that the aspect ratio between width and height and downScaledWidth and downScaledHeight should remain the same. By default, the region spans the whole image and is not scaled down.
qrEngineA manually created QR scanner engine instance to be reused. This improves performance if you're scanning a lot of images. An engine can be manually created via QrScanner.createQrEngine(QrScanner.WORKER_PATH). By default, no engine is reused for single image scanning.
canvasA manually created canvas to be reused. This improves performance if you're scanning a lot of images. A canvas can be manually created via a <canvas> tag in your markup or document.createElement('canvas'). By default, no canvas is reused for single image scanning.
disallowCanvasResizingRequest a provided canvas for reuse to not be resized, irrespective of the source image or source region dimensions. Note that the canvas and source region should have the same aspect ratio to avoid that the image to scan gets distorted which could make detecting QR codes impossible. By default, the canvas size is adapted to the scan region dimensions or down scaled scan region for single image scanning.
alsoTryWithoutScanRegionRequest a second scan on the entire image if a scanRegion was provided and no QR code was found within that region. By default, no second scan is attempted.
returnDetailedScanResultEnforce reporting detailed scan results, see below.

To use the default value for an option, omit it or supply undefined.

Returned results depend on whether an options object was provided:

  • If no options object was provided, the result is a string with the read QR code's content. The simple string return type is for backwards compatibility, is now deprecated and will be removed in the future.
  • If an options object was provided the result is an object with properties data which is the read QR code's string content and cornerPoints which are the corner points of the read QR code's outline on the camera stream.

To avoid usage of the deprecated api if you're not supplying any other options, you can supply { returnDetailedScanResult: true } to enable the new api and get the detailed scan result.

If no QR code could be read, scanImage throws.

Checking for Camera availability

This library provides a utility method for checking whether the device has a camera. This can be useful for determining whether to offer the QR web cam scanning functionality to a user.

QrScanner.hasCamera(); // async

Getting the list of available Cameras

This library provides a utility method for getting a list of the device's cameras, defined via their id and label. This can be useful for letting a user choose a specific camera to use.

You can optionally request the camera's labels. Note that this however requires the user's permission to access the cameras, which he will be asked for if not granted already. If not specifically requested, device labels are determined on a best effort basis, i.e. actual labels are returned if permissions were already granted and fallback labels otherwise. If you want to request camera labels, it's recommendable to call listCameras after a QrScanner instance was successfully started, as by then the user will already have given his permission.

QrScanner.listCameras(); // async; without requesting camera labels
QrScanner.listCameras(true); // async; requesting camera labels, potentially asking the user for permission

Specifying which camera to use

You can change the preferred camera to be used. The preference can be either a device id as returned by listCameras or a facing mode specified as 'environment' or 'user'. Note that there is no guarantee that the preference can actually be fulfilled.

qrScanner.setCamera(facingModeOrDeviceId); // async

Color Inverted Mode

The scanner by default scans for dark QR codes on a bright background. You can change this behavior to scan for bright QR codes on dark background or for both at the same time:

qrScanner.setInversionMode(inversionMode);

Where inversionMode can be original, invert or both. The default for web cam scanning is original and for single image scanning both.

Color Correction

Change the weights for red, green and blue in the grayscale computation to improve contrast for QR codes of a specific color:

qrScanner.setGrayscaleWeights(red, green, blue, useIntegerApproximation = true);

Where red, green and blue should sum up to 256 if useIntegerApproximation === true and 1 otherwise. By default, these values are used.

Flashlight support

On supported browsers, you can check whether the currently used camera has a flash and turn it on or off. Note that hasFlash should be called after the scanner was successfully started to avoid the need to open a temporary camera stream just to query whether it has flash support, potentially asking the user for camera access.

qrScanner.hasFlash(); // check whether the browser and used camera support turning the flash on; async.
qrScanner.isFlashOn(); // check whether the flash is on
qrScanner.turnFlashOn(); // turn the flash on if supported; async
qrScanner.turnFlashOff(); // turn the flash off if supported; async
qrScanner.toggleFlash(); // toggle the flash if supported; async.

Clean Up

You can destroy the QR scanner if you don't need it anymore:

qrScanner.destroy();
qrScanner = null;

This will stop the camera stream and web worker and cleans up event listeners. The QR scanner will be dysfunctional after it has been destroyed.

Build the project

The project is prebuild in qr-scanner.min.js in combination with qr-scanner-worker.min.js. Building yourself is only necessary if you want to change the code in the /src folder. NodeJs is required for building.

Install required build packages:

yarn

Building:

yarn build

NPM DownloadsLast 30 Days