feat(renderer): make logo optional

This commit is contained in:
Pihkaal
2024-10-12 17:05:56 +02:00
parent 1dfae1a9f5
commit 7b79354e84
4 changed files with 35 additions and 29 deletions

View File

@@ -7,7 +7,7 @@ export const LOGO_PADDING = 1;
export const renderQRCodeToCanvas = async (
canvas: HTMLCanvasElement | Canvas,
content: string,
logoUrl: string,
logoUrl: string | undefined,
) => {
await QRCode.toCanvas(canvas, content, {
errorCorrectionLevel: "H",
@@ -15,31 +15,33 @@ export const renderQRCodeToCanvas = async (
margin: 1,
});
const qrCode = QRCode.create(content, { errorCorrectionLevel: "H" });
const moduleCount = qrCode.modules.size + 2;
if (logoUrl) {
const qrCode = QRCode.create(content, { errorCorrectionLevel: "H" });
const moduleCount = qrCode.modules.size + 2;
const logoImage = await loadImage(logoUrl);
const logoImage = await loadImage(logoUrl);
const moduleSize = CANVAS_SIZE / moduleCount;
const moduleSize = CANVAS_SIZE / moduleCount;
let logoModules = Math.floor(moduleCount * 0.3);
if (logoModules % 2 !== moduleCount % 2) {
logoModules += 1;
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") as CanvasRenderingContext2D;
ctx.fillStyle = "white";
ctx.fillRect(
backgroundPosition,
backgroundPosition,
backgroundSize,
backgroundSize,
);
ctx.drawImage(logoImage, logoPosition, logoPosition, logoSize, logoSize);
}
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);
};

View File

@@ -54,7 +54,7 @@ export type ImageFormat = (typeof IMAGE_FORMATS)[number];
export const settingsSchema = z.object({
format: z.enum(IMAGE_FORMATS).default("png"),
logo: z.enum(LOGOS),
logo: z.enum(LOGOS).optional(),
content: z.string().min(1, "Required"),
});