Day 17 - canvas 文字换行

程序码

今天来学习文字换行

export default function App() {
  const canvasRef = useRef(null);
  useEffect(() => {
    if (canvasRef?.current) {
      const canvas = canvasRef?.current;
      const ctx = canvas.getContext("2d");
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.fillStyle = "gray";
      ctx.font = "30px Arial";
      ctx.lineWidth = 1;
      const str =
        "来到第十七篇了罗!铁人赛真的好辛苦!!神人们真的太神了~~~~";
      ctx.fillText(str, 0, 50);
    }
  }, [canvasRef]);

  return (
    <div className="App">
      <canvas
        ref={canvasRef}
        id="canvas"
        style={{ border: "solid 1px blue" }}
        width="300"
        height="300"
      ></canvas>
    </div>
  );
}

在一般填上文字的时候,是无法自己换行的,需要进行运算才可以达到完整显示文字的效果。

  /*
str:要绘制的字串
canvas:canvas物件
initX:绘制字串起始x座标
initY:绘制字串起始y座标
lineHeight:字行高,自己定义个值即可
*/
  const canvasTextAutoLine = (str, canvas, initX, initY, lineHeight) => {
    var ctx = canvas.getContext("2d");
    var lineWidth = 0;
    var canvasWidth = canvas.width;
    var lastSubStrIndex = 0;
    for (let i = 0; i < str.length; i++) {
      lineWidth += ctx.measureText(str[i]).width;
      if (lineWidth > canvasWidth - initX) {
        //减去initX,防止边界出现的问题
        ctx.fillText(str.substring(lastSubStrIndex, i), initX, initY);
        initY += lineHeight;
        lineWidth = 0;
        lastSubStrIndex = i;
      }
      if (i === str.length - 1) {
        ctx.fillText(str.substring(lastSubStrIndex, i + 1), initX, initY);
      }
    }
  };

把刚才的 fillText 替换成 canvasTextAutoLine,从程序码可以发现,我们使用宽度与文字去计算,超过就进行换行,来达到效果。

完成啦~~~

完整程序码 codesandbox

碎碎念时间

/images/emoticon/emoticon13.gif
前两篇因为时间的关系,给自己太难得题目,白天又忙得不可开交,造成无法做出成果,如果未来几天还有时间会回头补上... ,不知不觉已经过了二分之一的赛程了,再接再厉!


<<:  人脸辨识-day17 应用层面--3

>>:  [Day17] Sorting Band Names without articles

计算机概论 - 资料抽象化 data abstractions

除了连续储存的储存方式之外,本章将探讨电脑主记忆体其他存放资料的方式,所以主题会是资料结构,而其目的...

Day28 ATT&CK for ICS - Command and Control

Command and Control 攻击者已经进入工控环境之後,从自己的服务器传送指令给受害主机...

[13th][Day4] defer fallthrough

defer 延迟执行 Golang 有个很方便的东东:defer,他执行的时间点会是在离开目前的 f...

Day-9 Divide-and-Conquer-4 : Quicksort, 随机化Quicksort

Quicksort- Tony Hoare - 1962 和merge-sort一样,他使用了Div...

Day 09 : 资料库 Postgres

接着进入一个全新的篇章,介绍一下资料库。其中资料分析基础能力之一是可以从资料库拿取资料,因此我们需要...