Blog by ScanApp Free online QR Code and Barcode scanner for web

Setting dynamic QR box size in Html5-qrcode

mebjas/html5-qrcode is a fairly used open source library for implementing QR Code or barcode scanner in a web application.

Figure: User interface for Html5-qrcode using Html5QrcodeScanner class

The library provides two approaches for integrating QR code / bar code scanning with any web applications.

  1. Core library called Html5Qrcode which provide APIs for web developers to build the user interface upon and abstracts camera / permissions / QR code or barcode decoding.
  2. End to end UI for code scanning as well local image based scanning using Html5QrcodeScanner class.

One can simply setup a QR code scanning with following lines of code.

<!-- html -->
<div id="reader" width="600px"></div>
<script src="https://unpkg.com/html5-qrcode" type="text/javascript">
// Javascript code.

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: 250, height: 250} };
let html5QrcodeScanner = new Html5QrcodeScanner(
  "reader", config, /* verbose= */ false);
html5QrcodeScanner.render(onScanSuccess);

The qrbox config lets developers define the portion of the viewfinder that will be used for scanning. It’s supported both in Html5Qrcode as well as Html5QrcodeScanner class. Based on this value the library renders a box with shaded regions around it, allowing end-users to compose the scanning device around the QR code or barcodes.

qrbox configuration

Based on the developer documentation you can either pass a dimension of type QrDimensions as value for this config.

/** Defines dimension for QR Code Scanner. */
interface QrDimensions {
  width: number;
  height: number;
}

So this means for a barcode scanning usecase you can pass a non square configuration like {width: 400, height: 100} to render scanner like this - likely ideal for scanning rectangual barcodes.

Dynamically setting qrbox configuration

With version 2.2.0 onwards the library now also supports passing in a function of type QrDimensionFunction as a value for this configuration.

/**
 * 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;

The function takes in the dimensions of the viewfinder (the video stream with camera feed) and is expected to return QrDimensions.

This is great, with this you can now set a custom function to determine the QR box dimensions based on run time properties of the video stream that works across form factors.

Here’s an example:

function onScanSuccess(decodedText, decodedResult) {
    // handle the scanned code as you like, for example:
    console.log(`Code matched = ${decodedText}`, decodedResult);
}

// Square QR box with edge size = 70% of the smaller edge of the viewfinder.
let qrboxFunction = function(viewfinderWidth, viewfinderHeight) {
    let minEdgePercentage = 0.7; // 70%
    let minEdgeSize = Math.min(viewfinderWidth, viewfinderHeight);
    let qrboxSize = Math.floor(minEdgeSize * minEdgePercentage);
    return {
        width: qrboxSize,
        height: qrboxSize
    };
}

let html5QrcodeScanner = new Html5QrcodeScanner(
    "reader",
    { fps: 10, qrbox: qrboxFunction },
    /* verbose= */ false);
html5QrcodeScanner.render(onScanSuccess);

With this you can set the QR box dimensions to always be 70% of the smaller edge of the video stream so it works on both mobile and PC platforms.

Open source library for QR Code and barcode scanning with ReactJs

This article has been forked from the original article by the Author at blog.minhazav.dev.


Introduction

I don’t think ReactJs needs any explanation here and throughout this article I’ll assume the readers have familiarity with React, Components, state, props etc.

If you are just interested in implementing QR code or barcode scanning on web without react, I recommend you read this article

Install the library using npm

First, install the latest version of the library in your React project, using npm

npm i html5-qrcode

Create a React component

Next step is to create a React that abstracts most of the scanner implementation. Let say we create a new file called Html5QrcodePlugin.jsx


// Html5QrcodePlugin.jsx

import { Html5QrcodeScanner } from "html5-qrcode";
import React from 'react';

const qrcodeRegionId = "html5qr-code-full-region";

class Html5QrcodePlugin extends React.Component {
    render() {
        return <div id={qrcodeRegionId} />;
    }

    componentWillUnmount() {
        // TODO(mebjas): See if there is a better way to handle
        //  promise in `componentWillUnmount`.
        this.html5QrcodeScanner.clear().catch(error => {
            console.error("Failed to clear html5QrcodeScanner. ", error);
        });
    }

    componentDidMount() {
        // Creates the configuration object for Html5QrcodeScanner.
        function createConfig(props) {
            var config = {};
            if (props.fps) {
            config.fps = props.fps;
            }
            if (props.qrbox) {
            config.qrbox = props.qrbox;
            }
            if (props.aspectRatio) {
            config.aspectRatio = props.aspectRatio;
            }
            if (props.disableFlip !== undefined) {
            config.disableFlip = props.disableFlip;
            }
            return config;
        }

        var config = createConfig(this.props);
        var verbose = this.props.verbose === true;

        // Suceess callback is required.
        if (!(this.props.qrCodeSuccessCallback )) {
            throw "qrCodeSuccessCallback is required callback.";
        }

        this.html5QrcodeScanner = new Html5QrcodeScanner(
            qrcodeRegionId, config, verbose);
        this.html5QrcodeScanner.render(
            this.props.qrCodeSuccessCallback,
            this.props.qrCodeErrorCallback);
    }
};

export default Html5QrcodePlugin;

Important note: html5-qrcode is an actively developed library. It’s advisable to subscribe to updates at mebjas/html5-qrcode so you can keep the React library up to date.

Use this plugin in your React App

I’ll assume you have an App.js that is the source component. You can add the new Component we just created.

class App extends React.Component {
    constructor(props) {
        super(props);

        // This binding is necessary to make `this` work in the callback.
        this.onNewScanResult = this.onNewScanResult.bind(this);
    }

    render() {
        return (<div>
            <h1>Html5Qrcode React example!</h1>
            <Html5QrcodePlugin 
                fps={10}
                qrbox={250}
                disableFlip={false}
                qrCodeSuccessCallback={this.onNewScanResult}/>
        </div>);
    }

    onNewScanResult(decodedText, decodedResult) {
        // Handle the result here.
    }
);

Passing around the callback

You might have seen the callback defined in the above section

// ... rest of the code 

    onNewScanResult(decodedText, decodedResult) {
        // Handle the result here.
    }

// ... rest of the code 

Use this callback to define rest of your business logic. Let say your use-case is to pass the newly scanned result and print in on a <table>, you’d want to pass around the data to a different component. You can find an example of this at scanapp-org/html5-qrcode-react.

Full code reference

The full example has been created at scanapp-org/html5-qrcode-react - you can use that as a good reference.

Credits

ScanApp - Free QR code and barcode scanner for web
scanapp.org is a free online QR code and barcode reader for web built using this library - try it out.

Closing note

I have to admit, I am not React savvy, if you see errors or know of better way to do things please suggest it using the comments or send a pull request to scanapp-org/html5-qrcode-react.