QR Code Generator

GitHub license npm scope

Fully-functional QR code generator for Node.js and the browser, with zero dependencies

Advanced options

@liquid-js/qrcode-generator provides two classes: QRCodeMinimal, and QRCode which adds the functionality to output the code as ASCII characters, a data url, img tag, svg, html table, or draw it to a canvas. Use the QRCode class when rendering the code using a builting method (see rendering), and QRCodeMinimal when rendering the code yourself.

Custom rendering

Previous examples present different ways to display a standard square black-and-white QR code, either in HTML or in a Node.js terminal. While this is useful if you want to simply show a QR code, it offers only basic control of the appearance and customisation. To customise the appearance and rendering of the generated QR code, you can implement a custom render function.

import { QRCodeMinimal } from '@liquid-js/qrcode-generator/lib/qrcode/QRCodeMinimal.js'

/**
 * Render QR code as round dots on a canvas
 */
function renderDots(
    qrCode: QRCodeMinimal,
    canvas: HTMLCanvasElement,
    {
        size = 10,
        color = 'red'
    }
) {
    // Get number of rows and columns
    const moduleCount = qrCode.getModuleCount()

    // Set canvas size
    canvas.width = canvas.height = moduleCount * size

    // Configure rendering context
    const ctx = canvas.getContext('2d')!
    ctx.fillStyle = color // Set color

    // Iterate over rows and columns
    for (let row = 0; row < moduleCount; row++) {
        for (let column = 0; column < moduleCount; column++) {
            // If the current position is dark, draw a dot
            if (qrCode.isDark(row, column)) {
                const cx = row * size + size / 2
                const cy = column * size + size / 2
                ctx.arc(cx, cy, size / 2, 0, 2 * Math.PI)
                ctx.fill()
            }
        }
    }
}

// Use QRCodeMinimal to reduce bundle size, since rendering methods won't be needed
const qr = new QRCodeMinimal()

qr.addData('http://example.com/')

renderDots(
    qr,
    document.querySelector<HTMLCanvasElement>('canvas#container')!,
    {
        size: 20,
        color: 'blue'
    }
)