Answer the question
In order to leave comments, you need to log in
How to divide a line in canvas and transfer it to a new one if the number of characters in a line is more than N?
The algorithm is to count the number of characters in a line, if the number of characters in a line is greater than N. Then find the nearest word that no longer fits in the number of characters and, starting from this word, transfer the remaining words to a new line.
Original line: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sit amet varius ligula. Aenean dapibus lacus vel metus rhoncus, et porta magna vehicula
Result:
Lorem ipsum dolor sit
amet, consectetur
adipiscing elit.
Aliquam sit amet
varius ligula. Aenean
dapibus lacus vel metus
rhoncus, et porta
magna vehicula
Answer the question
In order to leave comments, you need to log in
Once upon a time I made a function, but \n is used instead of auto-transfer, maybe this will suit you.
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")];
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question