pic1一般做应用推广时,都会做一个自己的推广二维码。由于每个人的推广二维码都不一样,这就需要前端用代码生成属于用户个人的推广二维码。话不多说,下面讲解如果用Creator 生成用户专属推广二维码,文章最后会给出Demo供大家参考。
二维码生成库
使用QRcode二维码生成库。不过这个库是H5专用的,不过我们可以曲线救国,使用Creator的画图组件cc.Graphics,把二维码画出来。下面给出如何通过Url得到二维码的黑白方块数据。
let qrcode = new QRCode(-1, QRErrorCorrectLevel.H);
qrcode.addData(url);
qrcode.make();
不过如果Url中带有中文内容,在生成二维码前就要把字符串转换成UTF-8,然后再生成二维码,即:
let url=toUtf8('Cocos Creator 教程:生成二维码');
还有要注意微博扫一扫:大约200 字以内,微信扫一扫:大约 160字以内,支付宝扫一扫:大约130字符以内,所以一般链接不能太长。
设置插件
这一步需要把QRcode设置成插件,看图pic2:
pic2.png
完整代码
cc.Class({
extends: cc.Component,
properties: {
},
// use this for initialization
onLoad() {
this.init('http://forum.cocos.com/t/topic/44304/9');
},
init(url){
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();
}
}
}
},
});
最后
如果还有讲解不明白的地方,可以下载Demo,进行查看。还有喜欢就动动手指点喜欢,关注我吧,我会不定时更新Cocos Creator教程。
网友评论