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
  },

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM