A version of the code by @crazy2be which also respects newline characters already in the string, so that for example "Hello\nWorld!"
becomes [ "Hello", "World" ]
function getLines(ctx, text, maxWidth) {
const groups = text.split('\n');
let lines = [];
groups.forEach((group) => {
const words = group.split(' ');
let currentLine = words[0];
for (let i = 1; i < words.length; i++) {
const word = words[i];
let width = ctx.measureText(currentLine + ' ' + word).width;
if (width < maxWidth) {
currentLine += ' ' + word;
} else {
lines.push(currentLine);
currentLine = word;
}
}
lines.push(currentLine);
});
return lines;
}