BarcodeGenerator.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import {JsBarcode} from "./external/JsBarcode/JsBarcode.js"
  2. import {qrcode} from "./external/qrcode";
  3. import {CanvasTGA} from "./CanvasTGA.js";
  4. export class BarcodeGenerator {
  5. constructor(type, content) {
  6. this.type = type;
  7. this.content = content;
  8. }
  9. createCanvas() {
  10. switch(this.type) {
  11. // case "PDF417":
  12. // return this._makePDF417();
  13. case "QR":
  14. return this._makeQr();
  15. default:
  16. return this._makeBarcode();
  17. }
  18. }
  19. _makePDF417() {
  20. PDF417.init(this.content);
  21. const {num_cols, num_rows, bcode} = PDF417.getBarcodeArray();
  22. const canvas = new CanvasTGA(num_cols * 3, num_rows * 2);
  23. canvas.fillStyle = "black";
  24. for(let i = 0; i < num_rows; i++) {
  25. for(let j = 0; j < num_cols; j++) {
  26. if(bcode[i][j] == 1)
  27. canvas.fillRect(3 * j, 2 * i, 3, 2);
  28. }
  29. }
  30. return this._processCanvas(canvas);
  31. }
  32. _makeQr() {
  33. const qr = qrcode(5, "L");
  34. qr.addData(this.content);
  35. qr.make();
  36. const count = qr.getModuleCount();
  37. const canvas = new CanvasTGA(count * 5, count * 5);
  38. qr.renderTo2dContext(canvas, 5);
  39. return this._processCanvas(canvas);
  40. }
  41. _makeBarcode() {
  42. const canvas = new CanvasTGA(1, 1);
  43. canvas.addPalette({
  44. "#ffffff": 0xFFFFFF,
  45. "#000000": 0x0
  46. });
  47. JsBarcode(canvas, this.content, {
  48. format: this.type,
  49. flat: this.type.startsWith("EAN"),
  50. height: 60,
  51. width: 2,
  52. displayValue: false
  53. });
  54. return this._processCanvas(canvas);
  55. }
  56. _processCanvas(canvas) {
  57. canvas = CanvasTGA.rotate90(canvas);
  58. if(canvas.height * 2 <= 480 && canvas.width * 2 <= 180) {
  59. // Scale x2
  60. console.log("Perform scale x2");
  61. const newCanvas = new CanvasTGA(canvas.width * 2, canvas.height * 2);
  62. newCanvas.addPalette(canvas.currentPalette);
  63. for(let x = 0; x < canvas.width; x++) {
  64. for(let y = 0; y < canvas.height; y++) {
  65. const val = canvas._getPixel(x, y);
  66. newCanvas.fillStyle = newCanvas.palette[val];
  67. newCanvas.fillRect(x * 2, y * 2, 2, 2);
  68. }
  69. }
  70. canvas = newCanvas;
  71. }
  72. return canvas;
  73. }
  74. }