canvas绘制文字,实现自动换行,并且添加高亮

4 篇文章 0 订阅
4 篇文章 0 订阅
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" href="/favicon.png" />
    <meta
      name="viewport"
      content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0"
    />
  </head>
  <body>
    <canvas id="myCanvas" width="350" height="500"></canvas>
    <script>
      const canvas = document.getElementById("myCanvas");
      const ctx = canvas.getContext("2d");
      const maxWidth = 350; // 单行最大宽度
      const fontSize = 16; // 字号
      const font = `${fontSize}px Arial`; // 字体设置

      ctx.font = font;
      ctx.fillStyle = "black"; // 初始文字颜色为黑色

      let textLength = false;

      const text =
        "这是一段较长的文本,需要在达到最大宽度时自动换行。这是一段较长的文本,需要在达到最大宽度时自动换行需要在达到最大宽度时自动换行。";
      let x = 10; // 起始 x 坐标
      let y = 100; // 起始 y 坐标
      let currentLineWidth = 0;

      for (let i = 0; i < text.length; i++) {
        const char = text[i];
        const charWidth = ctx.measureText(char).width;
        if (currentLineWidth + charWidth > maxWidth) {
          // 超出最大宽度,换行
          y += fontSize + 5; // 行高加 5 作为行间距
          currentLineWidth = 0; // 重置当前行宽度
        }

        ctx.fillText(char, x + currentLineWidth, y);
        currentLineWidth += charWidth;

        if (i === 4) {
          // 到达前5个字,切换颜色为红色
          ctx.fillStyle = "red";
        }

        if (
          i === text.length - 1 &&
          currentLineWidth + charWidth + fontSize > maxWidth //如果
        ) {
          textLength = true;
        }
      }

      ctx.fillStyle = "black"; // 恢复文字颜色为黑色
      if (textLength) {
        ctx.fillText("这是结尾的文字", x, (y += fontSize + 5));
      } else {
        ctx.fillText("这是结尾的文字", x + currentLineWidth, y);
      }
    </script>
  </body>
</html>

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值