html5网页及Cocos中生成二维码

背景

        H5中会遇到生成二维码的功能需求,如网页名片、双屏互动等场景。

实现方法

        主要用到一个生成二维码图片的插件QRCode.js(插件下载及文档说明在底部参考链接)。说两种使用环境,第一种是在网页中直接使用,第二种是在Cocos中使用。

        第一种,在网页中直接使用方法很简单,添加Dom结构,引入javascript库文件,然后设置调用参数即可,

// 设置参数方式
var qrcode = new QRCode('qrcode', {
  text: 'your content',  // 可以是地址链接
  width: 256,
  height: 256,
  colorDark : '#000000', // 前景颜色
  colorLight : '#ffffff' // 背景颜色
});

        第二种,在Cocos中,先使用插件算法库得到二维矩阵数据(由true和false组成),然后根据每个小块的值去判断采用前景色或者背景色用cc.Graphic绘图,也就是画黑白块。    

    // 生成二维码,url为二维码内容或者地址链接
    createQRCode: function(url){
        var qrcode = new QRCode(-1, QRErrorCorrectLevel.H);
        qrcode.addData(url);
        qrcode.make();

        var ctx = this.mGraphics.getComponent(cc.Graphics);

        // 计算组成二维码每个小块的尺寸
        var tileW = this.mGraphics.node.width / qrcode.getModuleCount();
        var tileH = this.mGraphics.node.height / qrcode.getModuleCount();

        // 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;
                } else {
                    ctx.fillColor = cc.Color.WHITE;
                }
                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();
            }
        }
    }


备注

        市面上有二维码接口提供商(微微二维码),按等级付费或者按次付费。

        二维码接口文档 & SDK下载:http://www.wwei.cn/qrcode-docsdk.html

        阿里云市场彩色二维码生成与解码:

        https://market.aliyun.com/products/57126001/cmapi021204.html#sku=yuncode1520400000


参考链接

        QRCode.js 生成二维码 - 前端开发仓库:http://code.ciaoca.com/javascript/qrcode/

        H5案例分享:生成简易二维码:https://www.h5anli.com/articles/201701/createqr.html

        Creator1.4单个Graphics的DrawCall...:http://forum.cocos.com/t/creator1-4-graphics-drawcall/44339

        二维码实现【纯js算法库+cc.Graphic实现】:http://forum.cocos.com/t/js-cc-graphic/51566

猜你喜欢

转载自blog.csdn.net/gaofei880219/article/details/80149758