| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- import qrcode from "./qrcode-generator";
- const cache = new Map<string, string>();
- type QrFactory = (
- typeNumber: number,
- errorCorrectionLevel: string
- ) => {
- addData: (data: string, mode?: string) => void;
- make: () => void;
- getModuleCount: () => number;
- isDark: (row: number, col: number) => boolean;
- };
- const createQr = qrcode as unknown as QrFactory;
- /**
- * Integer-module PNG for Lodop ADD_PRINT_IMAGE.
- * Avoids Lodop QRCode raster blur and canvas anti-aliasing.
- */
- export async function qrPngDataUrl(text: string, px = 640): Promise<string> {
- const key = `${px}|${text}`;
- const hit = cache.get(key);
- if (hit) {
- return hit;
- }
- const qr = createQr(0, "L");
- qr.addData(text, "Byte");
- qr.make();
- const count = qr.getModuleCount();
- const margin = 2;
- const n = count + margin * 2;
- const cell = Math.max(8, Math.floor(px / n));
- const size = cell * n;
- const canvas = document.createElement("canvas");
- canvas.width = size;
- canvas.height = size;
- const ctx = canvas.getContext("2d");
- if (!ctx) {
- throw new Error("无法生成二维码画布");
- }
- ctx.imageSmoothingEnabled = false;
- ctx.fillStyle = "#ffffff";
- ctx.fillRect(0, 0, size, size);
- ctx.fillStyle = "#000000";
- for (let row = 0; row < count; row++) {
- for (let col = 0; col < count; col++) {
- if (qr.isDark(row, col)) {
- ctx.fillRect((col + margin) * cell, (row + margin) * cell, cell, cell);
- }
- }
- }
- const url = canvas.toDataURL("image/png");
- cache.set(key, url);
- return url;
- }
|