js实现二维码生成
使用 QRCode.js 库生成二维码
QRCode.js 是一个轻量级的 JavaScript 库,用于生成二维码。它支持多种配置选项,如颜色、大小和纠错级别。
安装 QRCode.js:
npm install qrcode
基本用法示例:

// 引入库
import QRCode from 'qrcode';
// 生成二维码到Canvas
QRCode.toCanvas(document.getElementById('canvas'), 'https://example.com', {
width: 200,
color: {
dark: '#000000',
light: '#ffffff'
}
}, function (error) {
if (error) console.error(error);
});
// 生成二维码图片URL
QRCode.toDataURL('https://example.com', {
width: 200
}, function (err, url) {
if (err) throw err;
document.getElementById('qr-img').src = url;
});
使用原生Canvas API生成二维码
如果不依赖第三方库,可以通过Canvas API手动实现简单的二维码生成。
基础实现思路:

function generateQR(text, size) {
const canvas = document.createElement('canvas');
canvas.width = size;
canvas.height = size;
const ctx = canvas.getContext('2d');
// 简单示例:生成黑白方块图案
const moduleSize = size / 10; // 假设10x10模块
for (let y = 0; y < 10; y++) {
for (let x = 0; x < 10; x++) {
const shouldFill = (x + y) % 2 === 0; // 简单交替填充
ctx.fillStyle = shouldFill ? '#000' : '#fff';
ctx.fillRect(x * moduleSize, y * moduleSize, moduleSize, moduleSize);
}
}
return canvas;
}
// 使用示例
const qrCanvas = generateQR('test', 200);
document.body.appendChild(qrCanvas);
使用Web Component封装二维码生成器
创建可复用的二维码组件:
class QRCodeElement extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
}
static get observedAttributes() {
return ['data', 'size'];
}
attributeChangedCallback(name, oldValue, newValue) {
if (oldValue !== newValue) {
this.render();
}
}
render() {
const data = this.getAttribute('data') || '';
const size = parseInt(this.getAttribute('size')) || 200;
this.shadowRoot.innerHTML = `
<style>
:host { display: inline-block; }
canvas { width: 100%; height: auto; }
</style>
<canvas width="${size}" height="${size}"></canvas>
`;
QRCode.toCanvas(this.shadowRoot.querySelector('canvas'), data, {
width: size
});
}
}
customElements.define('qr-code', QRCodeElement);
使用方式:
<qr-code data="https://example.com" size="150"></qr-code>
注意事项
实际生产环境中建议使用成熟的二维码库,因为完整的二维码生成算法需要考虑:
- 不同版本的数据容量
- 纠错级别(L/M/Q/H)
- 掩码模式选择
- 格式和版本信息编码
- 最佳数据编码方式选择
对于简单需求,QRCode.js库已经足够应对大多数场景。原生实现仅适用于学习目的或非常简单的演示场景。






