DEV Community

TateLyman
TateLyman

Posted on

Build a QR Code Generator with Canvas API — No Libraries Needed

Why No Library?

Most QR code generators use qrcode.js or similar. But the Canvas API is powerful enough to do it from scratch, and you eliminate a dependency.

How QR Codes Work

A QR code is a 2D matrix of modules (black/white squares) that encode data using Reed-Solomon error correction.

The key steps:

  1. Encode the data into a binary stream
  2. Apply error correction (Reed-Solomon)
  3. Place modules in the matrix following the QR spec
  4. Add finder patterns (the three big squares in corners)
  5. Render to Canvas

Canvas Implementation

function renderQR(canvas, data, size = 256) {
  const ctx = canvas.getContext('2d');
  canvas.width = size;
  canvas.height = size;

  // Generate QR matrix (simplified)
  const matrix = generateMatrix(data);
  const moduleSize = size / matrix.length;

  // White background
  ctx.fillStyle = '#FFFFFF';
  ctx.fillRect(0, 0, size, size);

  // Draw modules
  ctx.fillStyle = '#000000';
  for (let row = 0; row < matrix.length; row++) {
    for (let col = 0; col < matrix[row].length; col++) {
      if (matrix[row][col]) {
        ctx.fillRect(
          col * moduleSize,
          row * moduleSize,
          moduleSize,
          moduleSize
        );
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Download as PNG

function downloadQR(canvas, filename = 'qrcode.png') {
  const link = document.createElement('a');
  link.download = filename;
  link.href = canvas.toDataURL('image/png');
  link.click();
}
Enter fullscreen mode Exit fullscreen mode

Live Demo

I built a full QR code generator using this approach — enter any text or URL and get a downloadable PNG:

devtools-site-delta.vercel.app/qr

Part of a collection of 22 free browser-based dev tools.

Top comments (0)