cocosCreator 版本:3.7.2
開發語言:typeScript
我們在游戲開發中,經常會生成一個專屬于玩家個人的二維碼,比如說推廣、充值等功能。
接到這個任務,在網上找了下,還是有很多教程的。但是這些教程大部分都是用QRCode二維碼生成庫,將js
文件設置成插件的形式。然后用畫圖組件Graphics
把二維碼畫出來。
我這里也是用的同樣的思路,但是沒有用插件的形式。下面說說具體的方法:
新建工程
打開cocosCreator,創建一個新工程。在scene
中添加一個精靈節點,將精靈設置為白色。再在精靈上添加一個Graphics
節點。如下圖
注意:這里要設置要精靈和繪圖節點的尺寸,最好是2的倍數,而且建議將
Graphics
的錨點設置為(0,0)
核心代碼
import { _decorator, Component, Node,Graphics, Color, UITransform } from 'cc';
import { QRCode } from './qr/QRCode';
const { ccclass, property } = _decorator;
let QRErrorCorrectLevel = {L: 1,M: 0,Q: 3,H: 2
};
@ccclass('qrCode')
export class qrCode extends Component {@property(Graphics)graphics:Graphics = null;start() {this.qrCode("https://lengmo714.top");}private qrCode(url) {let node = this.graphics;var qrcode = new QRCode(-1, QRErrorCorrectLevel.H);qrcode.addData(url);qrcode.make();var ctx = node.getComponent(Graphics)!;ctx.fillColor = Color.BLACK;var tileW = node.getComponent(UITransform)!.width / qrcode.getModuleCount();var tileH = node.getComponent(UITransform)!.height / qrcode.getModuleCount();// draw in the Graphicsfor (var row = 0; row < qrcode.getModuleCount(); row++) {for (var col = 0; col < qrcode.getModuleCount(); col++) {if (qrcode.isDark(row, col)) {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), Math.round(row * tileH), w, h);ctx.fill();} else {// ctx.fillColor = cc.Color.WHITE;}var w = (Math.ceil((col + 1) * tileW) - Math.floor(col * tileW));}}}
}
注意,這里還是要用到畫二維碼的插件庫,只是我沒有用這個插件庫,qrcode.js
代碼轉成了ts
代碼。
qrcode.js文件下載地址