mirror of
https://github.com/arthur-pbty/xiao.git
synced 2026-06-23 18:05:01 +02:00
Character Count, Nike Ad
This commit is contained in:
@@ -95,4 +95,32 @@ module.exports = class CanvasUtil {
|
||||
}
|
||||
return shorten ? `${text}...` : text;
|
||||
}
|
||||
|
||||
static wrapText(ctx, text, maxWidth) {
|
||||
if (ctx.measureText(text).width < maxWidth) return [text];
|
||||
const words = text.split(' ');
|
||||
const lines = [];
|
||||
let line = '';
|
||||
while (words.length > 0) {
|
||||
let split = false;
|
||||
while (ctx.measureText(words[0]).width >= maxWidth) {
|
||||
const temp = words[0];
|
||||
words[0] = temp.slice(0, -1);
|
||||
if (split) {
|
||||
words[1] = `${temp.slice(-1)}${words[1]}`;
|
||||
} else {
|
||||
split = true;
|
||||
words.splice(1, 0, temp.slice(-1));
|
||||
}
|
||||
}
|
||||
if (ctx.measureText(`${line}${words[0]}`).width < maxWidth) {
|
||||
line += `${words.shift()} `;
|
||||
} else {
|
||||
lines.push(line.trim());
|
||||
line = '';
|
||||
}
|
||||
if (words.length === 0) lines.push(line.trim());
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user