drawText(text) {
// If text is empty, not draw
if (text == "") return;
// Initialize text positions
let posX = TEXT_POS_X;
let posY = TEXT_POS_Y;
for (let i = 0; i < text.length; i++) {
// If letter eq new line, then change pos
if (text[i] == "\n") {
posX = TEXT_POS_X;
posY += GLYPH_H;
continue;
}
// If letter eq space, then change x pos
if (text[i] == " ") {
posX += SPACE_SIZE;
continue;
}
const [canvas, ctx] = createCanvas(GLYPH_W, GLYPH_H);
const meta = this.glyphs[text[i]];
// If glyph not found
if (meta == undefined) {
console.log(meta);
this.text_error = "Unknown glyph. See glyph_meta.json";
return;
}
// Clear error
this.text_error = "";
// Drawing letter in empty canvas
ctx.drawImage(
this.resources.fontColored,
meta[0] * GLYPH_W,
meta[1] * GLYPH_H,
GLYPH_W,
GLYPH_H,
0,
0,
GLYPH_W,
GLYPH_H
);
const trimmedCanvas = trim(canvas);
// Drawing letter
this.ctx.drawImage(trimmedCanvas, posX, posY);
posX += trimmedCanvas.width + GLYPH_MARGIN;
}
log(`Drawing text: ${text}`);
}
function createCanvas(width, height) {
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
return [canvas, canvas.getContext("2d")];
}