Word wrapping is unpleasant

This commit is contained in:
Dragon Fire
2024-04-21 18:02:36 -04:00
parent 5a10ec4949
commit 72be187f02
+30 -3
View File
@@ -220,15 +220,42 @@ module.exports = class CanvasUtil {
for (let j = 0; j < words.length; j++) {
const word = words[j];
if (ctx.measureText(`${currentLine} ${word}`).width <= maxWidth) {
currentLine += `${currentLine === '' ? '' : ' '}${word}`;
currentLine += `${currentLine === '' ? '' : ' '} ${word}`;
} else {
lines.push(currentLine.trim());
currentLine = word;
if (ctx.measureText(word).width > maxWidth) {
const chunks = [];
let currentChunk = '';
for (let k = 0; k < word.length; k++) {
const char = word[k];
if (ctx.measureText(`${currentChunk}${char}`).width <= maxWidth) {
currentChunk += char;
} else {
chunks.push(currentChunk);
currentChunk = char;
}
}
if (currentChunk !== '') {
chunks.push(currentChunk);
}
for (let k = 0; k < chunks.length; k++) {
if (ctx.measureText(`${currentLine} ${chunks[k]}`).width > maxWidth) {
lines.push(currentLine.trim());
currentLine = '';
}
currentLine += `${currentLine === '' ? '' : ' '} ${chunks[k]}`;
}
} else {
lines.push(currentLine.trim());
currentLine = word;
}
}
}
if (currentLine !== '') {
lines.push(currentLine.trim());
}
if (i < wordsAndBreaks.length - 1) {
lines.push('');
}
}
return lines;
}