qrcode.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import Frame from './frame.js'
  2. class Qrcode {
  3. constructor(params) {
  4. this.qrious = {
  5. 'foreground': '#000000',//填充颜色
  6. 'foregroundAlpha': 1,//透明度
  7. 'level': 'L', //纠错级别“L”“M”“Q”“H”
  8. 'padding': null,
  9. 'size': 100
  10. };
  11. if (params) {
  12. this.qrious = {...this.qrious, ...params}
  13. }
  14. }
  15. draw(canvasId, value) {
  16. let frame = new Frame({
  17. level: this.qrious.level,
  18. value: value
  19. });
  20. let i, j;
  21. let moduleSize = this._getModuleSize(frame);
  22. let offset = this._getOffset(frame);
  23. //console.log(offset,frame.width,moduleSize)
  24. this.ctx = uni.createCanvasContext(canvasId);
  25. this.ctx.setFillStyle(this.qrious.foreground);
  26. this.ctx.setGlobalAlpha(this.qrious.foregroundAlpha);
  27. for (i = 0; i < frame.width; i++) {
  28. for (j = 0; j < frame.width; j++) {
  29. if (frame.buffer[(j * frame.width) + i]) {
  30. this.ctx.fillRect((moduleSize * i) + offset, (moduleSize * j) + offset, moduleSize, moduleSize);
  31. }
  32. }
  33. }
  34. this.ctx.draw();
  35. }
  36. _getOffset(frame) {
  37. let qrious = this.qrious;
  38. let padding = qrious.padding;
  39. if (padding != null) {
  40. return padding;
  41. }
  42. let moduleSize = this._getModuleSize(frame);
  43. console.log(moduleSize, frame.width)
  44. let offset = Math.floor((qrious.size - (moduleSize * frame.width)) / 2);
  45. return Math.max(0, offset);
  46. }
  47. _getModuleSize(frame) {
  48. let qrious = this.qrious;
  49. let padding = qrious.padding || 0;
  50. let pixels = Math.floor((qrious.size - (padding * 2)) / frame.width);
  51. return Math.max(1, pixels);
  52. }
  53. clear() {
  54. this.ctx.clearRect(0, 0)
  55. }
  56. }
  57. export default Qrcode