Generate QR Codes in Cocos Creator with TypeScript and Graphics

  • Cocos Creator: 3.7.2
  • Language: TypeScript

Create a white Sprite, add a Graphics node, give both even dimensions, and preferably use a (0, 0) anchor for Graphics.

Scene setup

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import { _decorator, Component, Graphics, Color, UITransform } from 'cc';
import { QRCode } from './qr/QRCode';
const { ccclass, property } = _decorator;

@ccclass('QrCode')
export class QrCode extends Component {
  @property(Graphics) graphics: Graphics = null;

  start() { this.draw('https://lengmo714.top'); }

  private draw(url: string) {
    const qr = new QRCode(-1, 2);
    qr.addData(url);
    qr.make();
    const count = qr.getModuleCount();
    const transform = this.graphics.getComponent(UITransform);
    const tileW = transform.width / count;
    const tileH = transform.height / count;
    this.graphics.fillColor = Color.BLACK;

    for (let row = 0; row < count; row++) {
      for (let col = 0; col < count; col++) {
        if (!qr.isDark(row, col)) continue;
        const w = Math.ceil((col + 1) * tileW) - Math.floor(col * tileW);
        const h = Math.ceil((row + 1) * tileH) - Math.floor(row * tileH);
        this.graphics.rect(Math.round(col * tileW), Math.round(row * tileH), w, h);
        this.graphics.fill();
      }
    }
  }
}

QR library