Split string in JavaScript and detect line break

前端 未结 7 1171
情书的邮戳
情书的邮戳 2020-12-24 04:55

I have a small function I found that takes a string from a textarea and then puts it into a canvas element and wraps the text when the line gets to

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-24 05:06

    Here's the final code I [OP] used. Probably not best practice, but it worked.

    function wrapText(context, text, x, y, maxWidth, lineHeight) {
    
        var breaks = text.split('\n');
        var newLines = "";
        for(var i = 0; i < breaks.length; i ++){
          newLines = newLines + breaks[i] + ' breakLine ';
        }
    
        var words = newLines.split(' ');
        var line = '';
        console.log(words);
        for(var n = 0; n < words.length; n++) {
          if(words[n] != 'breakLine'){
            var testLine = line + words[n] + ' ';
            var metrics = context.measureText(testLine);
            var testWidth = metrics.width;
            if (testWidth > maxWidth && n > 0) {
              context.fillText(line, x, y);
              line = words[n] + ' ';
              y += lineHeight;
            }
            else {
              line = testLine;
            }
          }else{
              context.fillText(line, x, y);
              line = '';
              y += lineHeight;
          }
        }
        context.fillText(line, x, y);
      }
    

提交回复
热议问题