64 lines
1.8 KiB
TypeScript
64 lines
1.8 KiB
TypeScript
const {ccclass, property} = cc._decorator;
|
|
import { QR } from '../lib/qrcode';
|
|
|
|
@ccclass
|
|
export default class QRCodeComp extends cc.Component {
|
|
|
|
@property({
|
|
type: cc.Color
|
|
})
|
|
lightColor: cc.Color = cc.Color.WHITE
|
|
@property({
|
|
type: cc.Color
|
|
})
|
|
deepColor: cc.Color = cc.Color.BLACK
|
|
|
|
preVal:string = ''
|
|
|
|
// LIFE-CYCLE CALLBACKS:
|
|
|
|
// onLoad () {}
|
|
|
|
start () {
|
|
|
|
}
|
|
|
|
// update (dt) {}
|
|
showQr(val: string) {
|
|
if (this.preVal === val) {
|
|
return
|
|
}
|
|
this.preVal = val
|
|
var ec_level = 'Q';
|
|
var arr = QR(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 = cc.Color.BLACK;
|
|
} else {
|
|
ctx.fillColor = cc.Color.WHITE;
|
|
}
|
|
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();
|
|
}
|
|
}
|
|
}
|
|
}
|