You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1205 lines
42 KiB

4 months ago
  1. let QRCode = {};
  2. (function () {
  3. /**
  4. * 获取单个字符的utf8编码
  5. * unicode BMP平面约65535个字符
  6. * @param {num} code
  7. * return {array}
  8. */
  9. function unicodeFormat8(code) {
  10. // 1 byte
  11. var c0, c1, c2;
  12. if (code < 128) {
  13. return [code];
  14. // 2 bytes
  15. } else if (code < 2048) {
  16. c0 = 192 + (code >> 6);
  17. c1 = 128 + (code & 63);
  18. return [c0, c1];
  19. // 3 bytes
  20. } else {
  21. c0 = 224 + (code >> 12);
  22. c1 = 128 + (code >> 6 & 63);
  23. c2 = 128 + (code & 63);
  24. return [c0, c1, c2];
  25. }
  26. }
  27. /**
  28. * 获取字符串的utf8编码字节串
  29. * @param {string} string
  30. * @return {array}
  31. */
  32. function getUTF8Bytes(string) {
  33. var utf8codes = [];
  34. for (var i = 0; i < string.length; i++) {
  35. var code = string.charCodeAt(i);
  36. var utf8 = unicodeFormat8(code);
  37. for (var j = 0; j < utf8.length; j++) {
  38. utf8codes.push(utf8[j]);
  39. }
  40. }
  41. return utf8codes;
  42. }
  43. /**
  44. * 二维码算法实现
  45. * @param {string} data 要编码的信息字符串
  46. * @param {num} errorCorrectLevel 纠错等级
  47. */
  48. function QRCodeAlg(data, errorCorrectLevel) {
  49. this.typeNumber = -1; //版本
  50. this.errorCorrectLevel = errorCorrectLevel;
  51. this.modules = null; //二维矩阵,存放最终结果
  52. this.moduleCount = 0; //矩阵大小
  53. this.dataCache = null; //数据缓存
  54. this.rsBlocks = null; //版本数据信息
  55. this.totalDataCount = -1; //可使用的数据量
  56. this.data = data;
  57. this.utf8bytes = getUTF8Bytes(data);
  58. this.make();
  59. }
  60. QRCodeAlg.prototype = {
  61. constructor: QRCodeAlg,
  62. /**
  63. * 获取二维码矩阵大小
  64. * @return {num} 矩阵大小
  65. */
  66. getModuleCount: function () {
  67. return this.moduleCount;
  68. },
  69. /**
  70. * 编码
  71. */
  72. make: function () {
  73. this.getRightType();
  74. this.dataCache = this.createData();
  75. this.createQrcode();
  76. },
  77. /**
  78. * 设置二位矩阵功能图形
  79. * @param {bool} test 表示是否在寻找最好掩膜阶段
  80. * @param {num} maskPattern 掩膜的版本
  81. */
  82. makeImpl: function (maskPattern) {
  83. this.moduleCount = this.typeNumber * 4 + 17;
  84. this.modules = new Array(this.moduleCount);
  85. for (var row = 0; row < this.moduleCount; row++) {
  86. this.modules[row] = new Array(this.moduleCount);
  87. }
  88. this.setupPositionProbePattern(0, 0);
  89. this.setupPositionProbePattern(this.moduleCount - 7, 0);
  90. this.setupPositionProbePattern(0, this.moduleCount - 7);
  91. this.setupPositionAdjustPattern();
  92. this.setupTimingPattern();
  93. this.setupTypeInfo(true, maskPattern);
  94. if (this.typeNumber >= 7) {
  95. this.setupTypeNumber(true);
  96. }
  97. this.mapData(this.dataCache, maskPattern);
  98. },
  99. /**
  100. * 设置二维码的位置探测图形
  101. * @param {num} row 探测图形的中心横坐标
  102. * @param {num} col 探测图形的中心纵坐标
  103. */
  104. setupPositionProbePattern: function (row, col) {
  105. for (var r = -1; r <= 7; r++) {
  106. if (row + r <= -1 || this.moduleCount <= row + r) continue;
  107. for (var c = -1; c <= 7; c++) {
  108. if (col + c <= -1 || this.moduleCount <= col + c) continue;
  109. if ((0 <= r && r <= 6 && (c == 0 || c == 6)) || (0 <= c && c <= 6 && (r == 0 || r == 6)) || (2 <= r && r <= 4 && 2 <= c && c <= 4)) {
  110. this.modules[row + r][col + c] = true;
  111. } else {
  112. this.modules[row + r][col + c] = false;
  113. }
  114. }
  115. }
  116. },
  117. /**
  118. * 创建二维码
  119. * @return {[type]} [description]
  120. */
  121. createQrcode: function () {
  122. var minLostPoint = 0;
  123. var pattern = 0;
  124. var bestModules = null;
  125. for (var i = 0; i < 8; i++) {
  126. this.makeImpl(i);
  127. var lostPoint = QRUtil.getLostPoint(this);
  128. if (i == 0 || minLostPoint > lostPoint) {
  129. minLostPoint = lostPoint;
  130. pattern = i;
  131. bestModules = this.modules;
  132. }
  133. }
  134. this.modules = bestModules;
  135. this.setupTypeInfo(false, pattern);
  136. if (this.typeNumber >= 7) {
  137. this.setupTypeNumber(false);
  138. }
  139. },
  140. /**
  141. * 设置定位图形
  142. * @return {[type]} [description]
  143. */
  144. setupTimingPattern: function () {
  145. for (var r = 8; r < this.moduleCount - 8; r++) {
  146. if (this.modules[r][6] != null) {
  147. continue;
  148. }
  149. this.modules[r][6] = (r % 2 == 0);
  150. if (this.modules[6][r] != null) {
  151. continue;
  152. }
  153. this.modules[6][r] = (r % 2 == 0);
  154. }
  155. },
  156. /**
  157. * 设置矫正图形
  158. * @return {[type]} [description]
  159. */
  160. setupPositionAdjustPattern: function () {
  161. var pos = QRUtil.getPatternPosition(this.typeNumber);
  162. for (var i = 0; i < pos.length; i++) {
  163. for (var j = 0; j < pos.length; j++) {
  164. var row = pos[i];
  165. var col = pos[j];
  166. if (this.modules[row][col] != null) {
  167. continue;
  168. }
  169. for (var r = -2; r <= 2; r++) {
  170. for (var c = -2; c <= 2; c++) {
  171. if (r == -2 || r == 2 || c == -2 || c == 2 || (r == 0 && c == 0)) {
  172. this.modules[row + r][col + c] = true;
  173. } else {
  174. this.modules[row + r][col + c] = false;
  175. }
  176. }
  177. }
  178. }
  179. }
  180. },
  181. /**
  182. * 设置版本信息7以上版本才有
  183. * @param {bool} test 是否处于判断最佳掩膜阶段
  184. * @return {[type]} [description]
  185. */
  186. setupTypeNumber: function (test) {
  187. var bits = QRUtil.getBCHTypeNumber(this.typeNumber);
  188. for (var i = 0; i < 18; i++) {
  189. var mod = (!test && ((bits >> i) & 1) == 1);
  190. this.modules[Math.floor(i / 3)][i % 3 + this.moduleCount - 8 - 3] = mod;
  191. this.modules[i % 3 + this.moduleCount - 8 - 3][Math.floor(i / 3)] = mod;
  192. }
  193. },
  194. /**
  195. * 设置格式信息纠错等级和掩膜版本
  196. * @param {bool} test
  197. * @param {num} maskPattern 掩膜版本
  198. * @return {}
  199. */
  200. setupTypeInfo: function (test, maskPattern) {
  201. var data = (QRErrorCorrectLevel[this.errorCorrectLevel] << 3) | maskPattern;
  202. var bits = QRUtil.getBCHTypeInfo(data);
  203. // vertical
  204. for (var i = 0; i < 15; i++) {
  205. var mod = (!test && ((bits >> i) & 1) == 1);
  206. if (i < 6) {
  207. this.modules[i][8] = mod;
  208. } else if (i < 8) {
  209. this.modules[i + 1][8] = mod;
  210. } else {
  211. this.modules[this.moduleCount - 15 + i][8] = mod;
  212. }
  213. // horizontal
  214. var mod = (!test && ((bits >> i) & 1) == 1);
  215. if (i < 8) {
  216. this.modules[8][this.moduleCount - i - 1] = mod;
  217. } else if (i < 9) {
  218. this.modules[8][15 - i - 1 + 1] = mod;
  219. } else {
  220. this.modules[8][15 - i - 1] = mod;
  221. }
  222. }
  223. // fixed module
  224. this.modules[this.moduleCount - 8][8] = (!test);
  225. },
  226. /**
  227. * 数据编码
  228. * @return {[type]} [description]
  229. */
  230. createData: function () {
  231. var buffer = new QRBitBuffer();
  232. var lengthBits = this.typeNumber > 9 ? 16 : 8;
  233. buffer.put(4, 4); //添加模式
  234. buffer.put(this.utf8bytes.length, lengthBits);
  235. for (var i = 0, l = this.utf8bytes.length; i < l; i++) {
  236. buffer.put(this.utf8bytes[i], 8);
  237. }
  238. if (buffer.length + 4 <= this.totalDataCount * 8) {
  239. buffer.put(0, 4);
  240. }
  241. // padding
  242. while (buffer.length % 8 != 0) {
  243. buffer.putBit(false);
  244. }
  245. // padding
  246. while (true) {
  247. if (buffer.length >= this.totalDataCount * 8) {
  248. break;
  249. }
  250. buffer.put(QRCodeAlg.PAD0, 8);
  251. if (buffer.length >= this.totalDataCount * 8) {
  252. break;
  253. }
  254. buffer.put(QRCodeAlg.PAD1, 8);
  255. }
  256. return this.createBytes(buffer);
  257. },
  258. /**
  259. * 纠错码编码
  260. * @param {buffer} buffer 数据编码
  261. * @return {[type]}
  262. */
  263. createBytes: function (buffer) {
  264. var offset = 0;
  265. var maxDcCount = 0;
  266. var maxEcCount = 0;
  267. var length = this.rsBlock.length / 3;
  268. var rsBlocks = new Array();
  269. for (var i = 0; i < length; i++) {
  270. var count = this.rsBlock[i * 3 + 0];
  271. var totalCount = this.rsBlock[i * 3 + 1];
  272. var dataCount = this.rsBlock[i * 3 + 2];
  273. for (var j = 0; j < count; j++) {
  274. rsBlocks.push([dataCount, totalCount]);
  275. }
  276. }
  277. var dcdata = new Array(rsBlocks.length);
  278. var ecdata = new Array(rsBlocks.length);
  279. for (var r = 0; r < rsBlocks.length; r++) {
  280. var dcCount = rsBlocks[r][0];
  281. var ecCount = rsBlocks[r][1] - dcCount;
  282. maxDcCount = Math.max(maxDcCount, dcCount);
  283. maxEcCount = Math.max(maxEcCount, ecCount);
  284. dcdata[r] = new Array(dcCount);
  285. for (var i = 0; i < dcdata[r].length; i++) {
  286. dcdata[r][i] = 0xff & buffer.buffer[i + offset];
  287. }
  288. offset += dcCount;
  289. var rsPoly = QRUtil.getErrorCorrectPolynomial(ecCount);
  290. var rawPoly = new QRPolynomial(dcdata[r], rsPoly.getLength() - 1);
  291. var modPoly = rawPoly.mod(rsPoly);
  292. ecdata[r] = new Array(rsPoly.getLength() - 1);
  293. for (var i = 0; i < ecdata[r].length; i++) {
  294. var modIndex = i + modPoly.getLength() - ecdata[r].length;
  295. ecdata[r][i] = (modIndex >= 0) ? modPoly.get(modIndex) : 0;
  296. }
  297. }
  298. var data = new Array(this.totalDataCount);
  299. var index = 0;
  300. for (var i = 0; i < maxDcCount; i++) {
  301. for (var r = 0; r < rsBlocks.length; r++) {
  302. if (i < dcdata[r].length) {
  303. data[index++] = dcdata[r][i];
  304. }
  305. }
  306. }
  307. for (var i = 0; i < maxEcCount; i++) {
  308. for (var r = 0; r < rsBlocks.length; r++) {
  309. if (i < ecdata[r].length) {
  310. data[index++] = ecdata[r][i];
  311. }
  312. }
  313. }
  314. return data;
  315. },
  316. /**
  317. * 布置模块构建最终信息
  318. * @param {} data
  319. * @param {} maskPattern
  320. * @return {}
  321. */
  322. mapData: function (data, maskPattern) {
  323. var inc = -1;
  324. var row = this.moduleCount - 1;
  325. var bitIndex = 7;
  326. var byteIndex = 0;
  327. for (var col = this.moduleCount - 1; col > 0; col -= 2) {
  328. if (col == 6) col--;
  329. while (true) {
  330. for (var c = 0; c < 2; c++) {
  331. if (this.modules[row][col - c] == null) {
  332. var dark = false;
  333. if (byteIndex < data.length) {
  334. dark = (((data[byteIndex] >>> bitIndex) & 1) == 1);
  335. }
  336. var mask = QRUtil.getMask(maskPattern, row, col - c);
  337. if (mask) {
  338. dark = !dark;
  339. }
  340. this.modules[row][col - c] = dark;
  341. bitIndex--;
  342. if (bitIndex == -1) {
  343. byteIndex++;
  344. bitIndex = 7;
  345. }
  346. }
  347. }
  348. row += inc;
  349. if (row < 0 || this.moduleCount <= row) {
  350. row -= inc;
  351. inc = -inc;
  352. break;
  353. }
  354. }
  355. }
  356. }
  357. };
  358. /**
  359. * 填充字段
  360. */
  361. QRCodeAlg.PAD0 = 0xEC;
  362. QRCodeAlg.PAD1 = 0x11;
  363. //---------------------------------------------------------------------
  364. // 纠错等级对应的编码
  365. //---------------------------------------------------------------------
  366. var QRErrorCorrectLevel = [1, 0, 3, 2];
  367. //---------------------------------------------------------------------
  368. // 掩膜版本
  369. //---------------------------------------------------------------------
  370. var QRMaskPattern = {
  371. PATTERN000: 0,
  372. PATTERN001: 1,
  373. PATTERN010: 2,
  374. PATTERN011: 3,
  375. PATTERN100: 4,
  376. PATTERN101: 5,
  377. PATTERN110: 6,
  378. PATTERN111: 7
  379. };
  380. //---------------------------------------------------------------------
  381. // 工具类
  382. //---------------------------------------------------------------------
  383. var QRUtil = {
  384. /*
  385. 每个版本矫正图形的位置
  386. */
  387. PATTERN_POSITION_TABLE: [
  388. [],
  389. [6, 18],
  390. [6, 22],
  391. [6, 26],
  392. [6, 30],
  393. [6, 34],
  394. [6, 22, 38],
  395. [6, 24, 42],
  396. [6, 26, 46],
  397. [6, 28, 50],
  398. [6, 30, 54],
  399. [6, 32, 58],
  400. [6, 34, 62],
  401. [6, 26, 46, 66],
  402. [6, 26, 48, 70],
  403. [6, 26, 50, 74],
  404. [6, 30, 54, 78],
  405. [6, 30, 56, 82],
  406. [6, 30, 58, 86],
  407. [6, 34, 62, 90],
  408. [6, 28, 50, 72, 94],
  409. [6, 26, 50, 74, 98],
  410. [6, 30, 54, 78, 102],
  411. [6, 28, 54, 80, 106],
  412. [6, 32, 58, 84, 110],
  413. [6, 30, 58, 86, 114],
  414. [6, 34, 62, 90, 118],
  415. [6, 26, 50, 74, 98, 122],
  416. [6, 30, 54, 78, 102, 126],
  417. [6, 26, 52, 78, 104, 130],
  418. [6, 30, 56, 82, 108, 134],
  419. [6, 34, 60, 86, 112, 138],
  420. [6, 30, 58, 86, 114, 142],
  421. [6, 34, 62, 90, 118, 146],
  422. [6, 30, 54, 78, 102, 126, 150],
  423. [6, 24, 50, 76, 102, 128, 154],
  424. [6, 28, 54, 80, 106, 132, 158],
  425. [6, 32, 58, 84, 110, 136, 162],
  426. [6, 26, 54, 82, 110, 138, 166],
  427. [6, 30, 58, 86, 114, 142, 170]
  428. ],
  429. G15: (1 << 10) | (1 << 8) | (1 << 5) | (1 << 4) | (1 << 2) | (1 << 1) | (1 << 0),
  430. G18: (1 << 12) | (1 << 11) | (1 << 10) | (1 << 9) | (1 << 8) | (1 << 5) | (1 << 2) | (1 << 0),
  431. G15_MASK: (1 << 14) | (1 << 12) | (1 << 10) | (1 << 4) | (1 << 1),
  432. /*
  433. BCH编码格式信息
  434. */
  435. getBCHTypeInfo: function (data) {
  436. var d = data << 10;
  437. while (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G15) >= 0) {
  438. d ^= (QRUtil.G15 << (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G15)));
  439. }
  440. return ((data << 10) | d) ^ QRUtil.G15_MASK;
  441. },
  442. /*
  443. BCH编码版本信息
  444. */
  445. getBCHTypeNumber: function (data) {
  446. var d = data << 12;
  447. while (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G18) >= 0) {
  448. d ^= (QRUtil.G18 << (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G18)));
  449. }
  450. return (data << 12) | d;
  451. },
  452. /*
  453. 获取BCH位信息
  454. */
  455. getBCHDigit: function (data) {
  456. var digit = 0;
  457. while (data != 0) {
  458. digit++;
  459. data >>>= 1;
  460. }
  461. return digit;
  462. },
  463. /*
  464. 获取版本对应的矫正图形位置
  465. */
  466. getPatternPosition: function (typeNumber) {
  467. return QRUtil.PATTERN_POSITION_TABLE[typeNumber - 1];
  468. },
  469. /*
  470. 掩膜算法
  471. */
  472. getMask: function (maskPattern, i, j) {
  473. switch (maskPattern) {
  474. case QRMaskPattern.PATTERN000:
  475. return (i + j) % 2 == 0;
  476. case QRMaskPattern.PATTERN001:
  477. return i % 2 == 0;
  478. case QRMaskPattern.PATTERN010:
  479. return j % 3 == 0;
  480. case QRMaskPattern.PATTERN011:
  481. return (i + j) % 3 == 0;
  482. case QRMaskPattern.PATTERN100:
  483. return (Math.floor(i / 2) + Math.floor(j / 3)) % 2 == 0;
  484. case QRMaskPattern.PATTERN101:
  485. return (i * j) % 2 + (i * j) % 3 == 0;
  486. case QRMaskPattern.PATTERN110:
  487. return ((i * j) % 2 + (i * j) % 3) % 2 == 0;
  488. case QRMaskPattern.PATTERN111:
  489. return ((i * j) % 3 + (i + j) % 2) % 2 == 0;
  490. default:
  491. throw new Error("bad maskPattern:" + maskPattern);
  492. }
  493. },
  494. /*
  495. 获取RS的纠错多项式
  496. */
  497. getErrorCorrectPolynomial: function (errorCorrectLength) {
  498. var a = new QRPolynomial([1], 0);
  499. for (var i = 0; i < errorCorrectLength; i++) {
  500. a = a.multiply(new QRPolynomial([1, QRMath.gexp(i)], 0));
  501. }
  502. return a;
  503. },
  504. /*
  505. 获取评价
  506. */
  507. getLostPoint: function (qrCode) {
  508. var moduleCount = qrCode.getModuleCount(),
  509. lostPoint = 0,
  510. darkCount = 0;
  511. for (var row = 0; row < moduleCount; row++) {
  512. var sameCount = 0;
  513. var head = qrCode.modules[row][0];
  514. for (var col = 0; col < moduleCount; col++) {
  515. var current = qrCode.modules[row][col];
  516. //level 3 评价
  517. if (col < moduleCount - 6) {
  518. if (current && !qrCode.modules[row][col + 1] && qrCode.modules[row][col + 2] && qrCode.modules[row][col + 3] && qrCode.modules[row][col + 4] && !qrCode.modules[row][col + 5] && qrCode.modules[row][col + 6]) {
  519. if (col < moduleCount - 10) {
  520. if (qrCode.modules[row][col + 7] && qrCode.modules[row][col + 8] && qrCode.modules[row][col + 9] && qrCode.modules[row][col + 10]) {
  521. lostPoint += 40;
  522. }
  523. } else if (col > 3) {
  524. if (qrCode.modules[row][col - 1] && qrCode.modules[row][col - 2] && qrCode.modules[row][col - 3] && qrCode.modules[row][col - 4]) {
  525. lostPoint += 40;
  526. }
  527. }
  528. }
  529. }
  530. //level 2 评价
  531. if ((row < moduleCount - 1) && (col < moduleCount - 1)) {
  532. var count = 0;
  533. if (current) count++;
  534. if (qrCode.modules[row + 1][col]) count++;
  535. if (qrCode.modules[row][col + 1]) count++;
  536. if (qrCode.modules[row + 1][col + 1]) count++;
  537. if (count == 0 || count == 4) {
  538. lostPoint += 3;
  539. }
  540. }
  541. //level 1 评价
  542. if (head ^ current) {
  543. sameCount++;
  544. } else {
  545. head = current;
  546. if (sameCount >= 5) {
  547. lostPoint += (3 + sameCount - 5);
  548. }
  549. sameCount = 1;
  550. }
  551. //level 4 评价
  552. if (current) {
  553. darkCount++;
  554. }
  555. }
  556. }
  557. for (var col = 0; col < moduleCount; col++) {
  558. var sameCount = 0;
  559. var head = qrCode.modules[0][col];
  560. for (var row = 0; row < moduleCount; row++) {
  561. var current = qrCode.modules[row][col];
  562. //level 3 评价
  563. if (row < moduleCount - 6) {
  564. if (current && !qrCode.modules[row + 1][col] && qrCode.modules[row + 2][col] && qrCode.modules[row + 3][col] && qrCode.modules[row + 4][col] && !qrCode.modules[row + 5][col] && qrCode.modules[row + 6][col]) {
  565. if (row < moduleCount - 10) {
  566. if (qrCode.modules[row + 7][col] && qrCode.modules[row + 8][col] && qrCode.modules[row + 9][col] && qrCode.modules[row + 10][col]) {
  567. lostPoint += 40;
  568. }
  569. } else if (row > 3) {
  570. if (qrCode.modules[row - 1][col] && qrCode.modules[row - 2][col] && qrCode.modules[row - 3][col] && qrCode.modules[row - 4][col]) {
  571. lostPoint += 40;
  572. }
  573. }
  574. }
  575. }
  576. //level 1 评价
  577. if (head ^ current) {
  578. sameCount++;
  579. } else {
  580. head = current;
  581. if (sameCount >= 5) {
  582. lostPoint += (3 + sameCount - 5);
  583. }
  584. sameCount = 1;
  585. }
  586. }
  587. }
  588. // LEVEL4
  589. var ratio = Math.abs(100 * darkCount / moduleCount / moduleCount - 50) / 5;
  590. lostPoint += ratio * 10;
  591. return lostPoint;
  592. }
  593. };
  594. //---------------------------------------------------------------------
  595. // QRMath使用的数学工具
  596. //---------------------------------------------------------------------
  597. var QRMath = {
  598. /*
  599. 将n转化为a^m
  600. */
  601. glog: function (n) {
  602. if (n < 1) {
  603. throw new Error("glog(" + n + ")");
  604. }
  605. return QRMath.LOG_TABLE[n];
  606. },
  607. /*
  608. 将a^m转化为n
  609. */
  610. gexp: function (n) {
  611. while (n < 0) {
  612. n += 255;
  613. }
  614. while (n >= 256) {
  615. n -= 255;
  616. }
  617. return QRMath.EXP_TABLE[n];
  618. },
  619. EXP_TABLE: new Array(256),
  620. LOG_TABLE: new Array(256)
  621. };
  622. for (var i = 0; i < 8; i++) {
  623. QRMath.EXP_TABLE[i] = 1 << i;
  624. }
  625. for (var i = 8; i < 256; i++) {
  626. QRMath.EXP_TABLE[i] = QRMath.EXP_TABLE[i - 4] ^ QRMath.EXP_TABLE[i - 5] ^ QRMath.EXP_TABLE[i - 6] ^ QRMath.EXP_TABLE[i - 8];
  627. }
  628. for (var i = 0; i < 255; i++) {
  629. QRMath.LOG_TABLE[QRMath.EXP_TABLE[i]] = i;
  630. }
  631. //---------------------------------------------------------------------
  632. // QRPolynomial 多项式
  633. //---------------------------------------------------------------------
  634. /**
  635. * 多项式类
  636. * @param {Array} num 系数
  637. * @param {num} shift a^shift
  638. */
  639. function QRPolynomial(num, shift) {
  640. if (num.length == undefined) {
  641. throw new Error(num.length + "/" + shift);
  642. }
  643. var offset = 0;
  644. while (offset < num.length && num[offset] == 0) {
  645. offset++;
  646. }
  647. this.num = new Array(num.length - offset + shift);
  648. for (var i = 0; i < num.length - offset; i++) {
  649. this.num[i] = num[i + offset];
  650. }
  651. }
  652. QRPolynomial.prototype = {
  653. get: function (index) {
  654. return this.num[index];
  655. },
  656. getLength: function () {
  657. return this.num.length;
  658. },
  659. /**
  660. * 多项式乘法
  661. * @param {QRPolynomial} e 被乘多项式
  662. * @return {[type]} [description]
  663. */
  664. multiply: function (e) {
  665. var num = new Array(this.getLength() + e.getLength() - 1);
  666. for (var i = 0; i < this.getLength(); i++) {
  667. for (var j = 0; j < e.getLength(); j++) {
  668. num[i + j] ^= QRMath.gexp(QRMath.glog(this.get(i)) + QRMath.glog(e.get(j)));
  669. }
  670. }
  671. return new QRPolynomial(num, 0);
  672. },
  673. /**
  674. * 多项式模运算
  675. * @param {QRPolynomial} e 模多项式
  676. * @return {}
  677. */
  678. mod: function (e) {
  679. var tl = this.getLength(),
  680. el = e.getLength();
  681. if (tl - el < 0) {
  682. return this;
  683. }
  684. var num = new Array(tl);
  685. for (var i = 0; i < tl; i++) {
  686. num[i] = this.get(i);
  687. }
  688. while (num.length >= el) {
  689. var ratio = QRMath.glog(num[0]) - QRMath.glog(e.get(0));
  690. for (var i = 0; i < e.getLength(); i++) {
  691. num[i] ^= QRMath.gexp(QRMath.glog(e.get(i)) + ratio);
  692. }
  693. while (num[0] == 0) {
  694. num.shift();
  695. }
  696. }
  697. return new QRPolynomial(num, 0);
  698. }
  699. };
  700. //---------------------------------------------------------------------
  701. // RS_BLOCK_TABLE
  702. //---------------------------------------------------------------------
  703. /*
  704. 二维码各个版本信息[块数, 每块中的数据块数, 每块中的信息块数]
  705. */
  706. var RS_BLOCK_TABLE = [
  707. // L
  708. // M
  709. // Q
  710. // H
  711. // 1
  712. [1, 26, 19],
  713. [1, 26, 16],
  714. [1, 26, 13],
  715. [1, 26, 9],
  716. // 2
  717. [1, 44, 34],
  718. [1, 44, 28],
  719. [1, 44, 22],
  720. [1, 44, 16],
  721. // 3
  722. [1, 70, 55],
  723. [1, 70, 44],
  724. [2, 35, 17],
  725. [2, 35, 13],
  726. // 4
  727. [1, 100, 80],
  728. [2, 50, 32],
  729. [2, 50, 24],
  730. [4, 25, 9],
  731. // 5
  732. [1, 134, 108],
  733. [2, 67, 43],
  734. [2, 33, 15, 2, 34, 16],
  735. [2, 33, 11, 2, 34, 12],
  736. // 6
  737. [2, 86, 68],
  738. [4, 43, 27],
  739. [4, 43, 19],
  740. [4, 43, 15],
  741. // 7
  742. [2, 98, 78],
  743. [4, 49, 31],
  744. [2, 32, 14, 4, 33, 15],
  745. [4, 39, 13, 1, 40, 14],
  746. // 8
  747. [2, 121, 97],
  748. [2, 60, 38, 2, 61, 39],
  749. [4, 40, 18, 2, 41, 19],
  750. [4, 40, 14, 2, 41, 15],
  751. // 9
  752. [2, 146, 116],
  753. [3, 58, 36, 2, 59, 37],
  754. [4, 36, 16, 4, 37, 17],
  755. [4, 36, 12, 4, 37, 13],
  756. // 10
  757. [2, 86, 68, 2, 87, 69],
  758. [4, 69, 43, 1, 70, 44],
  759. [6, 43, 19, 2, 44, 20],
  760. [6, 43, 15, 2, 44, 16],
  761. // 11
  762. [4, 101, 81],
  763. [1, 80, 50, 4, 81, 51],
  764. [4, 50, 22, 4, 51, 23],
  765. [3, 36, 12, 8, 37, 13],
  766. // 12
  767. [2, 116, 92, 2, 117, 93],
  768. [6, 58, 36, 2, 59, 37],
  769. [4, 46, 20, 6, 47, 21],
  770. [7, 42, 14, 4, 43, 15],
  771. // 13
  772. [4, 133, 107],
  773. [8, 59, 37, 1, 60, 38],
  774. [8, 44, 20, 4, 45, 21],
  775. [12, 33, 11, 4, 34, 12],
  776. // 14
  777. [3, 145, 115, 1, 146, 116],
  778. [4, 64, 40, 5, 65, 41],
  779. [11, 36, 16, 5, 37, 17],
  780. [11, 36, 12, 5, 37, 13],
  781. // 15
  782. [5, 109, 87, 1, 110, 88],
  783. [5, 65, 41, 5, 66, 42],
  784. [5, 54, 24, 7, 55, 25],
  785. [11, 36, 12],
  786. // 16
  787. [5, 122, 98, 1, 123, 99],
  788. [7, 73, 45, 3, 74, 46],
  789. [15, 43, 19, 2, 44, 20],
  790. [3, 45, 15, 13, 46, 16],
  791. // 17
  792. [1, 135, 107, 5, 136, 108],
  793. [10, 74, 46, 1, 75, 47],
  794. [1, 50, 22, 15, 51, 23],
  795. [2, 42, 14, 17, 43, 15],
  796. // 18
  797. [5, 150, 120, 1, 151, 121],
  798. [9, 69, 43, 4, 70, 44],
  799. [17, 50, 22, 1, 51, 23],
  800. [2, 42, 14, 19, 43, 15],
  801. // 19
  802. [3, 141, 113, 4, 142, 114],
  803. [3, 70, 44, 11, 71, 45],
  804. [17, 47, 21, 4, 48, 22],
  805. [9, 39, 13, 16, 40, 14],
  806. // 20
  807. [3, 135, 107, 5, 136, 108],
  808. [3, 67, 41, 13, 68, 42],
  809. [15, 54, 24, 5, 55, 25],
  810. [15, 43, 15, 10, 44, 16],
  811. // 21
  812. [4, 144, 116, 4, 145, 117],
  813. [17, 68, 42],
  814. [17, 50, 22, 6, 51, 23],
  815. [19, 46, 16, 6, 47, 17],
  816. // 22
  817. [2, 139, 111, 7, 140, 112],
  818. [17, 74, 46],
  819. [7, 54, 24, 16, 55, 25],
  820. [34, 37, 13],
  821. // 23
  822. [4, 151, 121, 5, 152, 122],
  823. [4, 75, 47, 14, 76, 48],
  824. [11, 54, 24, 14, 55, 25],
  825. [16, 45, 15, 14, 46, 16],
  826. // 24
  827. [6, 147, 117, 4, 148, 118],
  828. [6, 73, 45, 14, 74, 46],
  829. [11, 54, 24, 16, 55, 25],
  830. [30, 46, 16, 2, 47, 17],
  831. // 25
  832. [8, 132, 106, 4, 133, 107],
  833. [8, 75, 47, 13, 76, 48],
  834. [7, 54, 24, 22, 55, 25],
  835. [22, 45, 15, 13, 46, 16],
  836. // 26
  837. [10, 142, 114, 2, 143, 115],
  838. [19, 74, 46, 4, 75, 47],
  839. [28, 50, 22, 6, 51, 23],
  840. [33, 46, 16, 4, 47, 17],
  841. // 27
  842. [8, 152, 122, 4, 153, 123],
  843. [22, 73, 45, 3, 74, 46],
  844. [8, 53, 23, 26, 54, 24],
  845. [12, 45, 15, 28, 46, 16],
  846. // 28
  847. [3, 147, 117, 10, 148, 118],
  848. [3, 73, 45, 23, 74, 46],
  849. [4, 54, 24, 31, 55, 25],
  850. [11, 45, 15, 31, 46, 16],
  851. // 29
  852. [7, 146, 116, 7, 147, 117],
  853. [21, 73, 45, 7, 74, 46],
  854. [1, 53, 23, 37, 54, 24],
  855. [19, 45, 15, 26, 46, 16],
  856. // 30
  857. [5, 145, 115, 10, 146, 116],
  858. [19, 75, 47, 10, 76, 48],
  859. [15, 54, 24, 25, 55, 25],
  860. [23, 45, 15, 25, 46, 16],
  861. // 31
  862. [13, 145, 115, 3, 146, 116],
  863. [2, 74, 46, 29, 75, 47],
  864. [42, 54, 24, 1, 55, 25],
  865. [23, 45, 15, 28, 46, 16],
  866. // 32
  867. [17, 145, 115],
  868. [10, 74, 46, 23, 75, 47],
  869. [10, 54, 24, 35, 55, 25],
  870. [19, 45, 15, 35, 46, 16],
  871. // 33
  872. [17, 145, 115, 1, 146, 116],
  873. [14, 74, 46, 21, 75, 47],
  874. [29, 54, 24, 19, 55, 25],
  875. [11, 45, 15, 46, 46, 16],
  876. // 34
  877. [13, 145, 115, 6, 146, 116],
  878. [14, 74, 46, 23, 75, 47],
  879. [44, 54, 24, 7, 55, 25],
  880. [59, 46, 16, 1, 47, 17],
  881. // 35
  882. [12, 151, 121, 7, 152, 122],
  883. [12, 75, 47, 26, 76, 48],
  884. [39, 54, 24, 14, 55, 25],
  885. [22, 45, 15, 41, 46, 16],
  886. // 36
  887. [6, 151, 121, 14, 152, 122],
  888. [6, 75, 47, 34, 76, 48],
  889. [46, 54, 24, 10, 55, 25],
  890. [2, 45, 15, 64, 46, 16],
  891. // 37
  892. [17, 152, 122, 4, 153, 123],
  893. [29, 74, 46, 14, 75, 47],
  894. [49, 54, 24, 10, 55, 25],
  895. [24, 45, 15, 46, 46, 16],
  896. // 38
  897. [4, 152, 122, 18, 153, 123],
  898. [13, 74, 46, 32, 75, 47],
  899. [48, 54, 24, 14, 55, 25],
  900. [42, 45, 15, 32, 46, 16],
  901. // 39
  902. [20, 147, 117, 4, 148, 118],
  903. [40, 75, 47, 7, 76, 48],
  904. [43, 54, 24, 22, 55, 25],
  905. [10, 45, 15, 67, 46, 16],
  906. // 40
  907. [19, 148, 118, 6, 149, 119],
  908. [18, 75, 47, 31, 76, 48],
  909. [34, 54, 24, 34, 55, 25],
  910. [20, 45, 15, 61, 46, 16]
  911. ];
  912. /**
  913. * 根据数据获取对应版本
  914. * @return {[type]} [description]
  915. */
  916. QRCodeAlg.prototype.getRightType = function () {
  917. for (var typeNumber = 1; typeNumber < 41; typeNumber++) {
  918. var rsBlock = RS_BLOCK_TABLE[(typeNumber - 1) * 4 + this.errorCorrectLevel];
  919. if (rsBlock == undefined) {
  920. throw new Error("bad rs block @ typeNumber:" + typeNumber + "/errorCorrectLevel:" + this.errorCorrectLevel);
  921. }
  922. var length = rsBlock.length / 3;
  923. var totalDataCount = 0;
  924. for (var i = 0; i < length; i++) {
  925. var count = rsBlock[i * 3 + 0];
  926. var dataCount = rsBlock[i * 3 + 2];
  927. totalDataCount += dataCount * count;
  928. }
  929. var lengthBytes = typeNumber > 9 ? 2 : 1;
  930. if (this.utf8bytes.length + lengthBytes < totalDataCount || typeNumber == 40) {
  931. this.typeNumber = typeNumber;
  932. this.rsBlock = rsBlock;
  933. this.totalDataCount = totalDataCount;
  934. break;
  935. }
  936. }
  937. };
  938. //---------------------------------------------------------------------
  939. // QRBitBuffer
  940. //---------------------------------------------------------------------
  941. function QRBitBuffer() {
  942. this.buffer = new Array();
  943. this.length = 0;
  944. }
  945. QRBitBuffer.prototype = {
  946. get: function (index) {
  947. var bufIndex = Math.floor(index / 8);
  948. return ((this.buffer[bufIndex] >>> (7 - index % 8)) & 1);
  949. },
  950. put: function (num, length) {
  951. for (var i = 0; i < length; i++) {
  952. this.putBit(((num >>> (length - i - 1)) & 1));
  953. }
  954. },
  955. putBit: function (bit) {
  956. var bufIndex = Math.floor(this.length / 8);
  957. if (this.buffer.length <= bufIndex) {
  958. this.buffer.push(0);
  959. }
  960. if (bit) {
  961. this.buffer[bufIndex] |= (0x80 >>> (this.length % 8));
  962. }
  963. this.length++;
  964. }
  965. };
  966. // xzedit
  967. let qrcodeAlgObjCache = [];
  968. /**
  969. * 二维码构造函数主要用于绘制
  970. * @param {参数列表} opt 传递参数
  971. * @return {}
  972. */
  973. QRCode = function (opt) {
  974. //设置默认参数
  975. this.options = {
  976. text: '',
  977. size: 256,
  978. correctLevel: 3,
  979. background: '#ffffff',
  980. foreground: '#000000',
  981. pdground: '#000000',
  982. image: '',
  983. imageSize: 30,
  984. canvasId: opt.canvasId,
  985. context: opt.context,
  986. usingComponents: opt.usingComponents,
  987. showLoading: opt.showLoading,
  988. loadingText: opt.loadingText,
  989. };
  990. if (typeof opt === 'string') { // 只编码ASCII字符串
  991. opt = {
  992. text: opt
  993. };
  994. }
  995. if (opt) {
  996. for (var i in opt) {
  997. this.options[i] = opt[i];
  998. }
  999. }
  1000. //使用QRCodeAlg创建二维码结构
  1001. var qrCodeAlg = null;
  1002. for (var i = 0, l = qrcodeAlgObjCache.length; i < l; i++) {
  1003. if (qrcodeAlgObjCache[i].text == this.options.text && qrcodeAlgObjCache[i].text.correctLevel == this.options.correctLevel) {
  1004. qrCodeAlg = qrcodeAlgObjCache[i].obj;
  1005. break;
  1006. }
  1007. }
  1008. if (i == l) {
  1009. qrCodeAlg = new QRCodeAlg(this.options.text, this.options.correctLevel);
  1010. qrcodeAlgObjCache.push({
  1011. text: this.options.text,
  1012. correctLevel: this.options.correctLevel,
  1013. obj: qrCodeAlg
  1014. });
  1015. }
  1016. /**
  1017. * 计算矩阵点的前景色
  1018. * @param {Obj} config
  1019. * @param {Number} config.row 点x坐标
  1020. * @param {Number} config.col 点y坐标
  1021. * @param {Number} config.count 矩阵大小
  1022. * @param {Number} config.options 组件的options
  1023. * @return {String}
  1024. */
  1025. let getForeGround = function (config) {
  1026. var options = config.options;
  1027. if (options.pdground && (
  1028. (config.row > 1 && config.row < 5 && config.col > 1 && config.col < 5) ||
  1029. (config.row > (config.count - 6) && config.row < (config.count - 2) && config.col > 1 && config.col < 5) ||
  1030. (config.row > 1 && config.row < 5 && config.col > (config.count - 6) && config.col < (config.count - 2))
  1031. )) {
  1032. return options.pdground;
  1033. }
  1034. return options.foreground;
  1035. }
  1036. // 创建canvas
  1037. let createCanvas = function (options) {
  1038. if(options.showLoading){
  1039. uni.showLoading({
  1040. title: options.loadingText,
  1041. mask: true
  1042. });
  1043. }
  1044. var ctx = uni.createCanvasContext(options.canvasId, options.context);
  1045. var count = qrCodeAlg.getModuleCount();
  1046. var ratioSize = options.size;
  1047. var ratioImgSize = options.imageSize;
  1048. //计算每个点的长宽
  1049. var tileW = (ratioSize / count).toPrecision(4);
  1050. var tileH = (ratioSize / count).toPrecision(4);
  1051. //绘制
  1052. for (var row = 0; row < count; row++) {
  1053. for (var col = 0; col < count; col++) {
  1054. var w = (Math.ceil((col + 1) * tileW) - Math.floor(col * tileW));
  1055. var h = (Math.ceil((row + 1) * tileW) - Math.floor(row * tileW));
  1056. var foreground = getForeGround({
  1057. row: row,
  1058. col: col,
  1059. count: count,
  1060. options: options
  1061. });
  1062. ctx.setFillStyle(qrCodeAlg.modules[row][col] ? foreground : options.background);
  1063. ctx.fillRect(Math.round(col * tileW), Math.round(row * tileH), w, h);
  1064. }
  1065. }
  1066. if (options.image) {
  1067. var x = Number(((ratioSize - ratioImgSize) / 2).toFixed(2));
  1068. var y = Number(((ratioSize - ratioImgSize) / 2).toFixed(2));
  1069. drawRoundedRect(ctx, x, y, ratioImgSize, ratioImgSize, 2, 6, true, true)
  1070. ctx.drawImage(options.image, x, y, ratioImgSize, ratioImgSize);
  1071. // 画圆角矩形
  1072. function drawRoundedRect(ctxi, x, y, width, height, r, lineWidth, fill, stroke) {
  1073. ctxi.setLineWidth(lineWidth);
  1074. ctxi.setFillStyle(options.background);
  1075. ctxi.setStrokeStyle(options.background);
  1076. ctxi.beginPath(); // draw top and top right corner
  1077. ctxi.moveTo(x + r, y);
  1078. ctxi.arcTo(x + width, y, x + width, y + r, r); // draw right side and bottom right corner
  1079. ctxi.arcTo(x + width, y + height, x + width - r, y + height, r); // draw bottom and bottom left corner
  1080. ctxi.arcTo(x, y + height, x, y + height - r, r); // draw left and top left corner
  1081. ctxi.arcTo(x, y, x + r, y, r);
  1082. ctxi.closePath();
  1083. if (fill) {
  1084. ctxi.fill();
  1085. }
  1086. if (stroke) {
  1087. ctxi.stroke();
  1088. }
  1089. }
  1090. }
  1091. setTimeout(() => {
  1092. ctx.draw(true, () => {
  1093. // 保存到临时区域
  1094. setTimeout(() => {
  1095. uni.canvasToTempFilePath({
  1096. width: options.width,
  1097. height: options.height,
  1098. destWidth: options.width,
  1099. destHeight: options.height,
  1100. canvasId: options.canvasId,
  1101. quality: Number(1),
  1102. success: function (res) {
  1103. if (options.cbResult) {
  1104. // 由于官方还没有统一此接口的输出字段,所以先判定下 支付宝为 res.apFilePath
  1105. if (!empty(res.tempFilePath)) {
  1106. options.cbResult(res.tempFilePath)
  1107. } else if (!empty(res.apFilePath)) {
  1108. options.cbResult(res.apFilePath)
  1109. } else {
  1110. options.cbResult(res.tempFilePath)
  1111. }
  1112. }
  1113. },
  1114. fail: function (res) {
  1115. if (options.cbResult) {
  1116. options.cbResult(res)
  1117. }
  1118. },
  1119. complete: function () {
  1120. uni.hideLoading();
  1121. },
  1122. }, options.context);
  1123. }, options.text.length + 100);
  1124. });
  1125. }, options.usingComponents ? 0 : 150);
  1126. }
  1127. createCanvas(this.options);
  1128. // 空判定
  1129. let empty = function (v) {
  1130. let tp = typeof v,
  1131. rt = false;
  1132. if (tp == "number" && String(v) == "") {
  1133. rt = true
  1134. } else if (tp == "undefined") {
  1135. rt = true
  1136. } else if (tp == "object") {
  1137. if (JSON.stringify(v) == "{}" || JSON.stringify(v) == "[]" || v == null) rt = true
  1138. } else if (tp == "string") {
  1139. if (v == "" || v == "undefined" || v == "null" || v == "{}" || v == "[]") rt = true
  1140. } else if (tp == "function") {
  1141. rt = false
  1142. }
  1143. return rt
  1144. }
  1145. };
  1146. QRCode.prototype.clear = function (fn) {
  1147. var ctx = uni.createCanvasContext(this.options.canvasId, this.options.context)
  1148. ctx.clearRect(0, 0, this.options.size, this.options.size)
  1149. ctx.draw(false, () => {
  1150. if (fn) {
  1151. fn()
  1152. }
  1153. })
  1154. };
  1155. })()
  1156. export default QRCode