Cocos Creator 教程:生成二维码

Cocos Creator 教程:生成二维码
96 Leo501 关注
2018.04.27 14:18* 字数 405 阅读 1662评论 0喜欢 6
一般做应用推广时,都会做一个自己的推广二维码。由于每个人的推广二维码都不一样,这就需要前端用代码生成属于用户个人的推广二维码。话不多说,下面讲解如何用Creator 生成用户专属推广二维码,文章最后会给出Demo供大家参考。
pic1
二维码生成库

使用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();
            }
        }
    }
},

});
注意:最好把节点长宽设置为2的倍数。不然可能会出现无法识别二维码

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值