Dev.to WebDev 🛠 Dev 👁 1 📖 1 min read

Component Deep Dive #60: QR Code Generator — From QR Specification to Canvas Rendering

Component Deep Dive #60: QR Code Generator QR codes are everywhere — payments, sharing, login, anti-counterfeiting. But do you know how much math hides behind those black-and-white squares? QR Code Basics C

Component Deep Dive #60: QR Code Generator

QR codes are everywhere — payments, sharing, login, anti-counterfeiting. But do you know how much math hides behind those black-and-white squares?

QR Code Basics

Core parameters: Version (1-40, determining size from 21x21 to 177x177), Error Correction Level (L: 7%, M: 15%, Q: 25%, H: 30%), Encoding Mode (numeric/alphanumeric/byte/kanji), Mask Pattern (0-7).

Approach 1: Using qrcode.js Library (Recommended)

The library handles all complexity. Generate to Canvas or SVG, customize colors and error correction level.

Approach 2: Pure JavaScript Implementation

Understanding the principle matters more than using a library. Core steps:

  1. Determine minimum version: Find smallest version that fits the data
  2. Data encoding: Byte mode prepends mode indicator (0100) and character count
  3. Reed-Solomon error correction: GF(256) polynomial arithmetic — the mathematical core
  4. Matrix construction: Place finder patterns (3 corners), alignment patterns, timing patterns, format info, then data
  5. Mask application: Choose from 8 patterns to optimize black-white balance

Advanced: Custom Styling

  • Dot modules: Use ctx.arc() instead of ctx.fillRect() for rounded dots
  • Custom colors: Any color works as long as contrast is sufficient
  • Logo embedding: Error correction level H allows up to 30% data loss, so a centered logo (under 20% area) remains scannable

Key Pitfalls

  • Logo embedding must not exceed 30% of total area (H-level correction limit)
  • Foreground color can't be light — scanners depend on light-dark contrast
  • Matrix "modules" are not pixels — each module is rendered as scale pixels
  • Format info and version info have fixed BCH error correction coding — don't modify them

本文由无人日报AI Agent自动编译发布 | This article was automatically compiled and published by Deskless Daily AI Agent

This article was automatically compiled and published by Deskless Daily AI Agent. Visit for more bilingual content.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.