生成艺术二维码的体验地址::http://yating.online/demo/qr/
喜欢的话,给个星吧~https://github.com/Chenyating/ART-QR-Code
体验图片:
存在问题:
1、目前仅适用于pc端;
2、内容过于复杂,可能无法识别出来;
3、有的二维码,用手机可以扫描出来,但是无法图片识别;
现在讲一下大概开发的过程:
用的数组比较多;主要都是用来记录小黑块;
array记录小黑的行列上色;
依次类推;
1、生成二维码,需要使用到QRCode.js:
QRCode.js 是一个用于生成二维码的 JavaScript 库。主要是通过获取 DOM 的标签,再通过 HTML5 Canvas 绘制而成,不依赖任何库。
基本的用法是:
var qrcode = new QRCode("test", {
text: "www.yating.online",
width: 128,
height: 128,
colorDark : "#000000",
colorLight : "#ffffff",
correctLevel : QRCode.CorrectLevel.H
});
Github 地址:https://github.com/davidshimjs/qrcodejs
绘制二维码以后需要使用回调函数的方法:
// html
var qrcode = new QRCode(document.getElementById("qrcode"), {
text: "www.yating.online",
width: 128,
height: 128,
colorDark : "#000000",
colorLight : "#ffffff",
correctLevel : QRCode.CorrectLevel.H
},function(src){
console.log(src)
//回调方法
});
因为最后导出的是以canvas的形式导出的二维码,很不方便我计算小黑快;
所以我在源码上面,改成最后以table的形式导出二维码,从而更方便计算小黑块的数目;
- 在源码中找到这个方法:Drawing.prototype.draw = function (oQRCode)
- 把里面的内容删掉替换成现有的导出table的方法,代码如下:
var _htOption = this._htOption;
var _el = this._el;
var nCount = oQRCode.getModuleCount();
var nWidth = Math.floor(_htOption.width / nCount);
var nHeight = Math.floor(_htOption.height / nCount);
var aHTML = ['<table id="tableQR" style="border:0;border-collapse:collapse;">'];
for (var row = 0; row < nCount; row++) {
aHTML.push('<tr>');
for (var col = 0; col < nCount; col++) {
aHTML.push('<td style="border:0;border-collapse:collapse;padding:0;margin:0;width:' + nWidth + 'px;height:' + nHeight + 'px;background-color:' + (oQRCode.isDark(row, col) ? _htOption.colorDark : _htOption.colorLight) + ';"></td>');
}
aHTML.push('</tr>');
}
aHTML.push('</table>');
_el.innerHTML = aHTML.join('');
// Fix the margin values as real size.
var elTable = _el.childNodes[0];
var nLeftMarginTable = (_htOption.width - elTable.offsetWidth) / 2;
var nTopMarginTable = (_htOption.height - elTable.offsetHeight) / 2;
if (nLeftMarginTable > 0 && nTopMarginTable > 0) {
elTable.style.margin = nTopMarginTable + "px " + nLeftMarginTable + "px";
}
this._bIsPainted = true;
2、计算二维码的小黑快;
通过得到tr的行数,我们就可以知道这个二维码是一个n*n的正方形;
然后在每个小方块的位置,记录在一个数组里。并且记录好该方块是否上色;
主要是接下来给二维码绘制图案起作用;
在最一开始的时候,我要先把3个码眼给保存下来,以后就不在对码眼区域的小黑块做统计了
// 首先把3个大框框保存下来;
if ((i < 7 && j < 7) || (i > this.arrayLength - 8 && j < 8) || (i < 8 && j > this.arrayLength - 8)) {
this.array[i][j][1] = 1;
}
array[i][j][0]=1:表示第i行j列的小方块是黑色的;
array[i][j][1]=1:表示第i行j列的小方块待会不做记录处理;
以此类推:
countWidth() {
var tr = $("#tableQR tbody").find("tr");
// 获取二维码一行的数量,从而得知是n*n个;设置一个n行n列的数组
this.arrayLength = tr.length;
// 开始遍历表格,把每一个td的上色情况存在array数组里;
this.array = [];
for (let i = 0; i < tr.length; i++) {
this.array[i] = [];
// 首先遍历tr数组
// console.log("第", i, "行")
for (let j = 0; j < tr[i].children.length; j++) {
this.array[i][j] = []; //第一个是上色情况,第二个是记录情况
// 遍历每个tr里的td,记录每个td的上色情况;
if (tr[i].children[j].style.backgroundColor == 'black') {
this.array[i][j][0] = 1;
this.array[i][j][1] = 0;
// this.array[i][j]= 1;
} else {
this.array[i][j][0]