Spent too much time trying to fix main thread offload crash

This commit is contained in:
2025-11-11 17:51:49 +01:00
parent db5ec89e78
commit abb42a49ec
7 changed files with 86 additions and 63 deletions

View File

@@ -5,7 +5,7 @@ import { createCanvas, loadImage, registerFont } from "canvas";
export class NameCardCreator {
constructor(templatePath) {
this.templatePath = templatePath;
this.loadFont("./wwwroot/assets/fonts/Fredoka/static/Fredoka-Bold.ttf")
this.loadFont("./wwwroot/assets/fonts/Fredoka/static/Fredoka-Bold.ttf");
}
loadFont(fontPath) {
@@ -13,27 +13,31 @@ export class NameCardCreator {
if (!fs.existsSync(fullPath)) {
throw new Error(`Font file not found at ${fullPath}`);
}
registerFont(fullPath, {family: "Fredoka Bold"});
registerFont(fullPath, { family: "Fredoka Bold" });
}
/**
* Crée la carte de bienvenue entièrement via Canvas
*
* @param avatarPath
* @param name
* @returns {Promise<Buffer>}
*/
async getWelcomeCard(avatarPath, name) {
let canvas, ctx, smallCanvas, smallCtx;
try {
const canvasWidth = 3000;
const canvasHeight = 1000;
const canvas = createCanvas(canvasWidth, canvasHeight);
const ctx = canvas.getContext("2d");
canvas = createCanvas(canvasWidth, canvasHeight);
ctx = canvas.getContext("2d");
const template = await loadImage(this.templatePath);
ctx.drawImage(template, 0, 0, canvasWidth, canvasHeight);
const avatarSize = 675;
const avatar = await loadImage(avatarPath);
const avatarX = 225;
const avatarY = (canvasHeight - avatarSize) / 2;
ctx.save();
ctx.beginPath();
ctx.arc(
@@ -63,11 +67,10 @@ export class NameCardCreator {
ctx.stroke();
const messageX = avatarX + 1525;
const messageY = (canvasHeight / 2)+75;
const messageY = (canvasHeight / 2) + 75;
ctx.fillStyle = "#ede6e6";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.font = '115px "Fredoka Bold"';
const lines = [`Welcome ${name}, to the`, "Spicy Jail ~"];
@@ -78,31 +81,24 @@ export class NameCardCreator {
ctx.fillText(line, messageX, startY + i * lineHeight);
});
const result = this.scallDown(canvas, 1500, 500)
smallCanvas = createCanvas(1500, 500);
smallCtx = smallCanvas.getContext("2d");
smallCtx.drawImage(canvas, 0, 0, 1500, 500);
fs.writeFileSync("./tests/result/namecard.png", result);
console.log("✅ Name card created: namecard.png");
return result;
return smallCanvas.toBuffer();
} catch (err) {
console.error("Error creating name card:", err);
throw err;
} finally {
canvas.width = 0;
canvas.height = 0;
smallCanvas.width = 0;
smallCanvas.height = 0;
canvas = null;
smallCanvas = null;
ctx = null;
smallCtx = null;
}
}
/**
*
* @param target
* @param width
* @param height
* @returns {Buffer}
*/
scallDown(target, width, height) {
const smallCanvas = createCanvas(width, height);
const smallCtx = smallCanvas.getContext('2d');
smallCtx.drawImage(target, 0, 0, width, height);
return smallCanvas.toBuffer();
}
}