const {ccclass, property} = cc._decorator; import { QR } from '../../lib/qrcode'; export interface IQRCfg{ val: string lightColor?: cc.Color deepColor?: cc.Color } @ccclass export default class QRCodeComp extends cc.Component { @property(cc.Color) lightColor: cc.Color = cc.Color.WHITE @property(cc.Color) deepColor: cc.Color = cc.Color.BLACK preVal:string = '' // LIFE-CYCLE CALLBACKS: // onLoad () {} start () { } // update (dt) {} renderQr(data: IQRCfg) { if (this.preVal === data.val) { return } this.preVal = data.val var ec_level = 'Q'; var arr = QR(data.val, ec_level); // [y][x] var ctx = this.node.getComponent(cc.Graphics); if (!ctx) { ctx = this.node.addComponent(cc.Graphics) ; } ctx.clear() // compute tileW/tileH based on node width and height var countX = arr[0].length; var countY = arr.length; const { width, height } = this.node; var tileW = width / countX; var tileH = height / countY; // draw in the Graphics for (var row = 0; row < countY; row++) { for (var col = 0; col < countX; col++) { // ctx.fillStyle = qrcode.isDark(row, col) ? options.foreground : options.background; if (arr[row][col]) { ctx.fillColor = data.deepColor || this.deepColor; } else { ctx.fillColor = data.lightColor || this.lightColor; } var w = (Math.ceil((col + 1) * tileW) - Math.floor(col * tileW)); var h = (Math.ceil((row + 1) * tileW) - Math.floor(row * tileW)); ctx.rect(Math.round(col * tileW) - width / 2, Math.round(row * tileH) - height / 2, w, h); ctx.fill(); } } } }