Character Count, Nike Ad

This commit is contained in:
Daniel Odendahl Jr
2018-09-12 02:43:28 +00:00
parent 6f3868e9f4
commit 3db61411d7
6 changed files with 127 additions and 2 deletions
+28
View File
@@ -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;
}
};