使用Cocos creator(JavaScript)生成二维码
本人使用Cocos creator 版本为1.9.3(理论上1.4版本以上均可)。废话不多说,下面直接进入正题。
测试结果
准备工作
首先大家要下载QRCode.js ,不清楚什么是QRCode.js的可以参考: https://www.runoob.com/w3cnote/javascript-qrcodejs-library.html,当然也可以使用下边提供的qrcode.js
.下载好之后导入项目中设置为插件.
主要代码
QRcodeUi.js
.
cc.Class({
extends: cc.Component,
properties: {
},
// use this for initialization
onLoad() {
this.init('https://blog.csdn.net/qq_14965517/article/details/103831427');
},
init(url){
//注意 最好把qrImage与qrcode的节点长宽设置为2的倍数。不然可能会出现无法识别二维码
var ctx = this.node.addComponent(cc.Graphics); //添加绘画组件
if (typeof (url) !== 'string') {
console.log('url is not string',url);
return;
}
this.QRCreate(ctx, url);
},
QRCreate(ctx, url) {
var qrcode = new QRCode(-1, QRErrorCorrectLevel.H);
qrcode.addData(url);
qrcode.make();
ctx.fillColor = cc.Color.BLACK;
//块宽高
var tileW = this.node.width / qrcode.getModuleCount();
var tileH = this.node.height / qrcode.getModuleCount();
// draw in the Graphics
for (var row = 0; row < qrcode.getModuleCount(); row++) {
for (var col = 0; col < qrcode.getModuleCount(); col++) {
if (qrcode.isDark(row, col)) {
// ctx.fillColor = cc.Color.BLACK;
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();
}
}
}
},
});
qrcode.js下载地址:https://download.csdn.net/download/qq_14965517/12084702.
github链接:https://github.com/nicejintian/QRCode.
码云链接:https://gitee.com/ls_qq2670813470/QRCode.
原文链接:https://blog.csdn.net/qq_14965517/article/details/103831427.