/** * weapp-qrcode * 基于QRCode.js的小程序二维码生成工具 */ import qrcode from 'qrcode-generator' function drawCanvas (options) { options = options || {} options = { width: options.width || 200, height: options.height || 200, canvasId: options.canvasId || 'qrcode', text: options.text || '', margin: options.margin || 0, foreground: options.foreground || '#000000', background: options.background || '#ffffff', context: options.context } if (!options.context) { console.error('请传入context对象') return } // 计算二维码大小 const typeNumber = 0 // 自动计算 const errorCorrectionLevel = 'H' const qr = qrcode(typeNumber, errorCorrectionLevel) qr.addData(options.text) qr.make() const count = qr.getModuleCount() const ctx = options.context const tileW = options.width / count const tileH = options.height / count // 清空画布 ctx.fillStyle = options.background ctx.fillRect(0, 0, options.width, options.height) // 绘制二维码 for (let row = 0; row < count; row++) { for (let col = 0; col < count; col++) { ctx.fillStyle = qr.isDark(row, col) ? options.foreground : options.background const w = Math.ceil((col + 1) * tileW) - Math.floor(col * tileW) const h = Math.ceil((row + 1) * tileH) - Math.floor(row * tileH) ctx.fillRect(Math.round(col * tileW), Math.round(row * tileH), w, h) } } } export default drawCanvas