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:
- Encode the data into a binary stream
- Apply error correction (Reed-Solomon)
- Place modules in the matrix following the QR spec
- Add finder patterns (the three big squares in corners)
- 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
);
}
}
}
}
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();
}
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)