79501681

Date: 2025-03-11 17:54:12
Score: 1
Natty:
Report link

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;
}
Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • User mentioned (1): @crazy2be
  • Low reputation (1):
Posted by: limes.pink