JS-在canvas中渲染文字的时候文本自动换行

  drawText: function (ctx, str, leftWidth, initHeight, titleHeight, canvasWidth) {
    var lineWidth = 0;
    var num = 1;
    var lastSubStrIndex = 0; //每次开始截取的字符串的索引
    str=str.replace(/s*/g,"");
    for (let i = 0; i < str.length; i++) {
      lineWidth += ctx.measureText(str[i]).width;
      if (lineWidth > canvasWidth) {
        num++;
        if (num < 3) {
          ctx.fillText(str.substring(lastSubStrIndex, i), leftWidth, initHeight); //绘制截取部分
        } else {
          ctx.fillText(str.substring(lastSubStrIndex, i-3) + "...", leftWidth, initHeight); //绘制截取部分
          return
        }
       
        initHeight += 26; //16为字体的高度
      
        
        lineWidth = 0;
        lastSubStrIndex = i;
        titleHeight += 30;
      }
      if (i == str.length - 1) { //绘制剩余部分
        ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight);
      }
    }
    // 标题border-bottom 线距顶部距离
    titleHeight = titleHeight + 10;
    return titleHeight
  },

  

原文地址:https://www.cnblogs.com/liuqingxia/p/15438832.html