html canvas添加文字(自动换行)

html canvas添加文字

遇到\r换行

超过宽度自动换行

<html>

<body>
  <img width="1070" height="1070" id="img" />
  <script type="text/javascript">
    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d");
    canvas.width = 1070;
    canvas.height = 1070;
    ctx.textAlign = "left";
    ctx.textBaseline = "top";

    let canvasWidth = 950; // 计算canvas的宽度
    let initHeight = 50; // 绘制字体距离canvas顶部初始的高度
    let left = 60;

    let lineWidth = 0;
    let lastSubStrIndex = 0;
    let title = "标题";
    let str = "党的二十大报告强调,全党必须牢记,坚持党的全面领导是坚持和发展中国特色社会主义的必由之路\r中国特色社会主义是实现中华民族伟大复兴的必由之路,团结奋斗是中国人民创造历史伟业的必由之路,贯彻新发展理念是新时代我国发展壮大的必由之路,全面从严治党是党永葆生机活力、走好新的赶考之路的必由之路。"; // 内容

    ctx.font = "bold 44px 宋体";
    ctx.fillStype = "#000";
    ctx.fillText(title, left, initHeight);
    initHeight += 52;
    ctx.font = "normal 36px 宋体";

    ctx.font = title;
    canvasWidth = 930; // 计算canvas的宽度
    left = 70;
    for (let i = 0; i < str.length; i++) {
      lineWidth += ctx.measureText(str[i]).width;

      let iswarp = false; // 下一个字符是否换行
      const next_ch = str[i];
      if (next_ch === "\r") {
        iswarp = true;
      }
      if (lineWidth > canvasWidth || iswarp) {
        ctx.fillText(str.substring(lastSubStrIndex, i), left, initHeight); // 绘制截取部分
        initHeight += 40; // 20为字体的高度
        lineWidth = 0;
        if (iswarp) {
          lastSubStrIndex = i + 1;
          i = i + 1;
        } else {
          lastSubStrIndex = i;
        }
      }
      if (i === str.length - 1) {
        // 绘制剩余部分
        ctx.fillText(str.substring(lastSubStrIndex, i + 1), left, initHeight);
      }
      
      const url = canvas.toDataURL("image/png");
      document.getElementById("img").src = url;
    }
  </script>
</body>
</html>

 

posted @ 2022-11-26 18:35  小水皮  阅读(853)  评论(0编辑  收藏  举报