Cocos Creator(JavaScript)生成二维码

使用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.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值