refactor(renderer): create canvas in renderer

This commit is contained in:
Pihkaal
2024-10-12 18:44:12 +02:00
parent d0855dde8c
commit 43ecff853e
3 changed files with 35 additions and 36 deletions

View File

@@ -1,47 +1,50 @@
import { loadImage, type Canvas, type CanvasRenderingContext2D } from "canvas";
import { createCanvas, loadImage } from "canvas";
import QRCode from "qrcode";
export const CANVAS_SIZE = 1000;
export const LOGO_PADDING = 1;
const CANVAS_SIZE = 1000;
const LOGO_PADDING = 1;
export const renderQRCodeToCanvas = async (
canvas: HTMLCanvasElement | Canvas,
content: string,
logoUrl: string | undefined,
) => {
const canvas = createCanvas(CANVAS_SIZE, CANVAS_SIZE);
await QRCode.toCanvas(canvas, content, {
errorCorrectionLevel: "H",
width: CANVAS_SIZE,
margin: 1,
});
if (logoUrl) {
const qrCode = QRCode.create(content, { errorCorrectionLevel: "H" });
const moduleCount = qrCode.modules.size + 2;
if (!logoUrl) return canvas;
const logoImage = await loadImage(logoUrl);
const qrCode = QRCode.create(content, { errorCorrectionLevel: "H" });
const moduleCount = qrCode.modules.size + 2;
const moduleSize = CANVAS_SIZE / moduleCount;
const logoImage = await loadImage(logoUrl);
let logoModules = Math.floor(moduleCount * 0.3);
if (logoModules % 2 !== moduleCount % 2) {
logoModules += 1;
}
const moduleSize = CANVAS_SIZE / moduleCount;
const backgroundSize = logoModules * moduleSize + 1;
const backgroundPosition = (moduleSize * (moduleCount - logoModules)) / 2;
const logoSize = backgroundSize - LOGO_PADDING * 2;
const logoPosition = backgroundPosition + LOGO_PADDING;
const ctx = canvas.getContext("2d") as CanvasRenderingContext2D;
ctx.fillStyle = "white";
ctx.fillRect(
backgroundPosition,
backgroundPosition,
backgroundSize,
backgroundSize,
);
ctx.drawImage(logoImage, logoPosition, logoPosition, logoSize, logoSize);
let logoModules = Math.floor(moduleCount * 0.3);
if (logoModules % 2 !== moduleCount % 2) {
logoModules += 1;
}
const backgroundSize = logoModules * moduleSize + 1;
const backgroundPosition = (moduleSize * (moduleCount - logoModules)) / 2;
const logoSize = backgroundSize - LOGO_PADDING * 2;
const logoPosition = backgroundPosition + LOGO_PADDING;
const ctx = canvas.getContext("2d");
ctx.fillStyle = "white";
ctx.fillRect(
backgroundPosition,
backgroundPosition,
backgroundSize,
backgroundSize,
);
ctx.drawImage(logoImage, logoPosition, logoPosition, logoSize, logoSize);
return canvas;
};