CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-qrcode

QR code generator for both server-side and client-side applications with multiple output formats including PNG, SVG, Canvas, and Terminal rendering.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

browser-rendering.mddocs/

Browser Canvas Rendering

Browser-specific QR code rendering functionality for HTML5 canvas elements and data URL generation. These functions provide client-side QR code generation and display capabilities.

Capabilities

Canvas Rendering

Renders QR codes directly to HTML5 canvas elements.

/**
 * Draws QR code to an existing canvas element
 * @param {HTMLCanvasElement} canvasElement - Canvas to draw on
 * @param {string|Array} text - Text to encode or segments
 * @param {Object} options - Rendering options
 * @param {Function} callback - Completion callback
 */
function toCanvas(canvasElement, text, options, callback);

/**
 * Creates a new canvas element with QR code
 * @param {string|Array} text - Text to encode or segments  
 * @param {Object} options - Rendering options
 * @param {Function} callback - Callback with (error, canvas)
 */
function toCanvas(text, options, callback);

Usage Examples:

// Draw to existing canvas
const canvas = document.getElementById('qr-canvas');
QRCode.toCanvas(canvas, 'Hello World', function (error) {
  if (error) console.error(error);
  console.log('QR code drawn to canvas');
});

// Create new canvas
QRCode.toCanvas('Hello World', { width: 256 }, function (error, canvas) {
  if (error) console.error(error);
  document.body.appendChild(canvas);
});

// With custom styling
QRCode.toCanvas(canvas, 'Styled QR', {
  color: {
    dark: '#000080',  // Dark blue modules
    light: '#FFFFFF'  // White background
  },
  width: 300,
  margin: 2
}, function (error) {
  if (error) console.error(error);
});

// Using Promises
try {
  const canvas = await QRCode.toCanvas('Hello World');
  document.body.appendChild(canvas);
} catch (error) {
  console.error(error);
}

Data URL Generation

Generates data URLs containing QR code images for use in img elements or direct display.

/**
 * Generates data URL from text using new canvas
 * @param {string|Array} text - Text to encode or segments
 * @param {Object} options - Generation options  
 * @param {Function} callback - Callback with (error, url)
 * @returns {Promise<string>} Data URL when using promises
 */
function toDataURL(text, options, callback);

/**
 * Generates data URL using existing canvas
 * @param {HTMLCanvasElement} canvasElement - Canvas to use
 * @param {string|Array} text - Text to encode or segments
 * @param {Object} options - Generation options
 * @param {Function} callback - Callback with (error, url)
 * @returns {Promise<string>} Data URL when using promises
 */
function toDataURL(canvasElement, text, options, callback);

Usage Examples:

// Generate PNG data URL
QRCode.toDataURL('Hello World', function (err, url) {
  if (err) throw err;
  
  const img = document.createElement('img');
  img.src = url;
  document.body.appendChild(img);
});

// Generate JPEG with quality setting
QRCode.toDataURL('Hello World', {
  type: 'image/jpeg',
  rendererOpts: {
    quality: 0.8
  }
}, function (err, url) {
  console.log(url); // data:image/jpeg;base64,/9j/4AAQSkZJRgABAQ...
});

// Generate WebP format
QRCode.toDataURL('Hello World', {
  type: 'image/webp',
  rendererOpts: {
    quality: 0.9
  }
}, function (err, url) {
  console.log(url); // data:image/webp;base64,UklGRj4...
});

// Using existing canvas
const canvas = document.getElementById('temp-canvas');
QRCode.toDataURL(canvas, 'Hello', { width: 200 }, function (err, url) {
  // Canvas is reused, URL contains the QR code
});

// Using Promises
try {
  const url = await QRCode.toDataURL('Hello World', {
    color: { dark: '#FF0000' },
    width: 300
  });
  console.log('Data URL:', url);
} catch (err) {
  console.error(err);
}

Browser-Specific Options

Image Format Options

Configure output image format and quality for data URLs:

interface DataURLOptions {
  /** Image MIME type */
  type?: 'image/png' | 'image/jpeg' | 'image/webp'; // Default: 'image/png'
  
  /** Format-specific rendering options */
  rendererOpts?: {
    /** Image quality for JPEG/WebP (0.0 to 1.0) */
    quality?: number; // Default: 0.92
  };
}

Examples:

// High-quality JPEG
const jpegUrl = await QRCode.toDataURL('text', {
  type: 'image/jpeg',
  rendererOpts: { quality: 0.95 }
});

// Compressed WebP
const webpUrl = await QRCode.toDataURL('text', {
  type: 'image/webp', 
  rendererOpts: { quality: 0.7 }
});

// PNG (default, no quality setting)
const pngUrl = await QRCode.toDataURL('text', {
  type: 'image/png'
});

Canvas Rendering Options

Standard rendering options apply to both canvas and data URL functions:

// Size and scaling
QRCode.toCanvas(canvas, 'text', {
  width: 400,      // Force specific width in pixels
  scale: 8,        // Scale factor (alternative to width)
  margin: 4        // Quiet zone size in modules
});

// Colors
QRCode.toCanvas(canvas, 'text', {
  color: {
    dark: '#000000FF',   // Dark modules (RGBA hex)
    light: '#FFFFFFFF'   // Light modules (RGBA hex)
  }
});

// Custom colors with transparency
QRCode.toCanvas(canvas, 'text', {
  color: {
    dark: '#FF0000FF',   // Red modules
    light: '#00000000'   // Transparent background
  }
});

Module Bundler Integration

Webpack/Browserify

// ES6 imports
import QRCode from 'qrcode';

// CommonJS
const QRCode = require('qrcode');

// Usage in modern frameworks
const generateQR = async (text) => {
  try {
    const canvas = await QRCode.toCanvas(text, { width: 256 });
    return canvas;
  } catch (err) {
    throw new Error(`QR generation failed: ${err.message}`);
  }
};

React Integration Example

import React, { useEffect, useRef } from 'react';
import QRCode from 'qrcode';

function QRCodeComponent({ text, options = {} }) {
  const canvasRef = useRef();
  
  useEffect(() => {
    if (canvasRef.current && text) {
      QRCode.toCanvas(canvasRef.current, text, options, (error) => {
        if (error) console.error('QR Code error:', error);
      });
    }
  }, [text, options]);
  
  return <canvas ref={canvasRef} />;
}

Vue Integration Example

import QRCode from 'qrcode';

export default {
  mounted() {
    this.generateQR();
  },
  methods: {
    async generateQR() {
      try {
        const canvas = this.$refs.qrCanvas;
        await QRCode.toCanvas(canvas, this.qrText, this.qrOptions);
      } catch (err) {
        console.error(err);
      }
    }
  }
};

Precompiled Bundle Usage

For direct browser usage without bundlers:

<!DOCTYPE html>
<html>
<head>
  <title>QR Code Example</title>
</head>
<body>
  <canvas id="qr-canvas"></canvas>
  <img id="qr-image" />

  <!-- Include QRCode library -->
  <script src="/node_modules/qrcode/build/qrcode.js"></script>
  <!-- Or from CDN -->
  <!-- <script src="https://cdn.jsdelivr.net/npm/qrcode@1.5.4/build/qrcode.min.js"></script> -->

  <script>
    // QRCode is now available globally
    const canvas = document.getElementById('qr-canvas');
    const img = document.getElementById('qr-image');

    // Draw to canvas
    QRCode.toCanvas(canvas, 'Hello World', function (error) {
      if (error) console.error(error);
      console.log('Canvas QR code generated');
    });

    // Generate image data URL
    QRCode.toDataURL('Hello World', function (error, url) {
      if (error) console.error(error);
      img.src = url;
    });
  </script>
</body>
</html>

Error Handling

Browser rendering functions can encounter specific errors:

// Canvas context errors
QRCode.toCanvas(invalidCanvas, 'text', function (err) {
  if (err) {
    console.log(err.message); // Canvas-related error
  }
});

// Image format errors
QRCode.toDataURL('text', { type: 'invalid/format' }, function (err, url) {
  if (err) {
    console.log(err.message); // Unsupported image format
  }
});

// Insufficient canvas size
QRCode.toCanvas(smallCanvas, 'large text', { width: 1000 }, function (err) {
  if (err) {
    console.log(err.message); // Canvas size limitations
  }
});

Browser Compatibility

The browser rendering functions support:

  • Internet Explorer 10+
  • Safari 5.1+
  • All evergreen browsers (Chrome, Firefox, Edge, Safari, Opera)

Features used:

  • HTML5 Canvas API
  • Canvas 2D rendering context
  • Data URL generation (canvas.toDataURL())
  • Promise support (when not using callbacks)

Install with Tessl CLI

npx tessl i tessl/npm-qrcode

docs

browser-rendering.md

configuration.md

core-generation.md

index.md

server-operations.md

string-rendering.md

tile.json