无法将文本放在 html 画布的矩形内

时间:2021-04-15 15:27:57

标签: javascript html canvas

如何将文本放入矩形内而不使其溢出?这个想法是能够根据给定的 x 和 y 在画布中的任何位置创建任何类型的文本。但我不能完全实现它的文本超出矩形。

<!DOCTYPE html>
<html>
  <body>
    <canvas
      id="DemoCanvas"
      width="500"
      height="500"
      style="background-color: white"
    ></canvas>
    <script>
      const canvas = document.getElementById("DemoCanvas");
      const ctx = canvas.getContext("2d");
      const p310 = {
        text: "test qetqwetqwet qwrqwrqwrwqetqwinti0wne q0wient wq0ient q0wient 0iqwne 0tiqnw",
        x: 10,
        y: 100,
        background: "#FFF",
      };
      drawRectangle(p310);
      function drawRectangle({
        c = ctx,
        text,
        x,
        y,
        font = "arial",
        size = 12,
        padding = 4,
        color = "#000",
        boxStyle = "#000",
        background = "",
        lineWidth = 2,
        width = 100,
      }) {
        const words = text.split(" ");
        const usedWords = [];
        c.font = size + "px " + font;
        c.textAlign = "center";
        c.textBaseline = "middle";
        c.fillStyle = color;
        let totalSize = 0;

        for (var n = 0; n < words.length; n++) {
          var metrics = c.measureText(words[n]);
          var testWidth = metrics.width;
          const line = testWidth > width ? words[n] : words[n]
          width = testWidth > width ? testWidth : width;
          totalSize += metrics.fontBoundingBoxAscent + metrics.fontBoundingBoxDescent;
          c.fillText(words[n], x + testWidth / 2 + padding, n > 0  ? y += 20 : y);
        }
        if (background) {
          c.fillStyle = background;
          c.fillRect(x, y, width + padding * 2, totalSize + padding * 2);
        }
        if (boxStyle) {
          c.strokeStyle = boxStyle;
          c.lineWidth = lineWidth;
          c.strokeRect(
            x - lineWidth / 2,
            y - lineWidth / 2,
            width + padding * 2 + lineWidth,
            totalSize+ padding * 2 + lineWidth
          );
        }
      }
    </script>
  </body>
</html>
我的期望是,如果我尝试创建一个带有文本 drawRectangle(...) 的矩形,文本不会超出矩形,并且矩形会自动调整到文本。

0 个答案:

没有答案