qrcanvas

repository·master·Indexed 19 days ago

https://github.com/gera2ld/qrcanvas

A pure JavaScript QR code generator that renders output to a canvas element, compatible with both browser and Node.js environments. It supports custom styling via QRCanvasOptions, including configurable colors, sizes, and visual effects like 'round', 'fusion', and 'spot'. Users can add center branding using text, images, or custom layers. In Node.js, it requires the node-canvas module and the setCanvasModule utility function to enable canvas support.

Tokens
2.3K
Snippets
10
Records
13
Agent score
62%

What's inside qrcanvas

  1. Use QRCanvas via CDN in the browser

    master

    Load the library directly in an HTML file using a CDN. The module is mounted to a global variable named qrcanvas. Note that when using the global variable, you access the generator via qrcanvas.qrcanvas().

    <div id="qrcode"></div>
    
    <script src="https://cdn.jsdelivr.net/npm/qrcanvas@3"></script>
    
    <script>
      const canvas = qrcanvas.qrcanvas({
        data: 'hello, world'
      });
      document.getElementById('qrcode').appendChild(canvas);
    </script>
  2. Generate QR Codes in Node.js

    master

    To use QRCanvas in a Node.js environment, you must install and use node-canvas. You must call setCanvasModule with the required canvas module to enable canvas support before generating a QR code.

    const fs = require('fs');
    const { qrcanvas, setCanvasModule } = require('qrcanvas');
    
    // Enable node-canvas
    setCanvasModule(require('canvas'));
    
    const canvas = qrcanvas({
      data: 'hello, world'
    });
    
    // canvas is an instance of `node-canvas`
    canvas.pngStream().pipe(fs.createWriteStream('qrcode.png'));
  3. Understand QRCanvasLayer and Layer Values

    master

    A QRCanvasLayer defines what is painted to a specific area of the canvas. This is used for complex backgrounds, foregrounds, or logos.

    Layer Types:

    1. QRCanvasFillLayer: Fills an area with a CSS style (e.g., 'black', 'red', 'rgba(0,0,0,0.5)').
    2. QRCanvasImageLayer: Paints a CanvasImageSource onto the layer.
    3. QRCanvasTextLayer: Renders text with specific QRCanvasDrawTextOptions (font size, family, color, etc.).

    Layer Positioning:

    Layers can be positioned using:

    • x, y: Pixel coordinates.
    • col, row: Column and row indices.
    • w, h: Width and height in pixels.
    • cols, rows: Width and height in columns/rows.

    QRCanvasLayerValue:

    Used for background and foreground properties. It can be:

    • A string (CSS color).
    • A CanvasImageSource.
    • A QRCanvasLayer.
    • An array of QRCanvasLayerValue.
  4. Generate a QR Code as a module

    master

    Import the qrcanvas function from the qrcanvas package. Call it with an options object containing the data string to receive a canvas element.

    import { qrcanvas } from 'qrcanvas';
    
    const canvas = qrcanvas({
      data: 'hello, world'
    });
    document.body.appendChild(canvas);
  5. Configure QRCanvasEffect

    master

    The QRCanvasEffect object allows you to apply visual transformations to the QR code. Supported built-in types are round, fusion, and spot.

    Properties:

    • type: The name of the effect ('round', 'fusion', or 'spot').
    • value: A ratio between 0 and 1.
    • foregroundLight: (Specific to spot effect) The foreground color for the light areas.
    • spotRatio: (Specific to spot effect) The percentage of a cell dedicated to the QR code data (ratio between 0.25 and 1). Defaults to 0.25.
    const effect: QRCanvasEffect = {
      type: 'spot',
      value: 0.5,
      foregroundLight: '#eeeeee',
      spotRatio: 0.4
    };
  6. Configure QRCanvasOptions

    master

    The QRCanvasOptions interface is the primary configuration object used to initialize or render a QR code. It controls the data encoding, visual dimensions, colors, and optional logos or effects.

    Key Options:

    • data: The string to encode (UTF-8).
    • typeNumber: The QR code version (0-40). 0 enables automatic selection. If the data is too large for the specified number, the smallest valid number will be used.
    • correctLevel: Error correction level ('L', 'M', 'Q', or 'H'). Note that assigning a logo automatically sets this to 'H'.
    • size: Total pixel width or height. Ignored if cellSize is provided.
    • cellSize: Pixel width/height of a single cell. If neither size nor cellSize is provided, a default value is used.
    • background / foreground: Can be a color string, a CanvasImageSource, a QRCanvasLayer, or an array of QRCanvasLayerValue.
    • padding: Space around the QR code.
    • logo: An optional logo to place in the center.
    • resize: Boolean indicating whether to resize the canvas to the QR code size on render.
    • effect: A QRCanvasEffect object to apply visual styles.
    const options: QRCanvasOptions = {
      data: 'https://example.com',
      typeNumber: 0,
      correctLevel: 'H',
      size: 300,
      background: 'white',
      foreground: 'black',
      logo: 'my-logo-text',
      effect: {
        type: 'round',
        value: 0.5
      }
    };
  7. Use QRCanvasLogo for center branding

    master

    The logo property in QRCanvasOptions accepts several types of input to place branding in the center of the QR code:

    • String: A simple text logo (e.g., 'hello').
    • Text Layer: A QRCanvasTextLayer for advanced text styling.
      logo = {
        text: 'hello, world',
        options: { color: 'green' }
      };
    • Image: A CanvasImageSource (like an HTMLImageElement or HTMLCanvasElement).
      logo = { image: loadedImageElement };
    • Layer: A QRCanvasLayer (Fill or Image layer) for custom positioning and sizing.
      logo = { style: 'red', x: 10, y: 10 };
    // Text logo with options
    logo = {
      text: 'hello, world',
      options: {
        color: 'green',
      },
    };
    
    // Image logo
    logo = { image: loadedImageElementOrCanvas };
    
    // Layer logo
    logo = { style: 'red' };
  8. Configure the canvas module for Node.js environments with setCanvasModule()

    master

    In Node.js environments where a native browser Canvas and Image API are not globally available, you must use setCanvasModule to provide the necessary canvas implementation. This function injects the required Canvas, Image, and createCanvas utilities into the internal helpers module so that qrcanvas can function correctly.

    Pass an object containing the following properties:

    • Canvas: The Canvas constructor/class.
    • Image: The Image constructor/class.
    • createCanvas: A function used to create new canvas instances.

    Once called, qrcanvas will use these provided implementations for all canvas-related operations.

    import { setCanvasModule } from './path-to-qrcanvas/util';
    import { Canvas, Image, createCanvas } from 'some-canvas-library'; // e.g., 'canvas'
    
    setCanvasModule({ Canvas, Image, createCanvas });
  9. Generate a QR code canvas with qrcanvas()

    master

    The qrcanvas function is the primary entrypoint for rendering a QR code onto an HTML <canvas> element. It accepts a QRCanvasOptions object which configures the QR code content and the visual rendering parameters.

    To use it, provide a canvas element, the desired size (total dimensions), and cellSize (the size of each individual QR module/pixel). Other properties in the options object are passed to the internal renderer to define the QR code data and styling.

    import { qrcanvas } from 'qrcanvas';
    
    // Assuming you have a canvas element in your DOM
    const canvas = document.getElementById('my-canvas') as HTMLCanvasElement;
    
    qrcanvas({
      canvas,
      size: 300,
      cellSize: 10,
      // ... other QRCanvasOptions like text, color, etc.
    });
  10. Import QRCanvas from the qrcanvas package

    master

    The qrcanvas package provides a unified entrypoint for all core functionality, including the main QRCanvas class, supporting types, and utility functions. You can import everything you need directly from the package root.

    import { QRCanvas, type QRCanvasOptions } from 'qrcanvas';