用 Javascript 解决

要将文本添加到 HTML <canvas> 元素,我们需要使用 fillText() 或者 strokeText() 方法,或者我们可以使用两者的组合。

我们还可以为文本添加颜色、定义字体和大小,甚至添加渐变。

在下面的示例中,我们为 <canvas> 元素提供了一个唯一的 id 属性,这使我们可以使用 Javascript 轻松访问该元素。

我们还设置了元素的宽度和高度。

使用 fillText() 方法在 <canvas> 元素上添加文本的示例:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <style>
      #canvas {
        background: #59b8de;
        width: 250;
        height: 150;
      }
    </style>
  </head>
  <body>
    <canvas id="canvas"></canvas>
    <script>
      var canvas = document.getElementById("canvas");
      var context = canvas.getContext("2d");
      context.fillStyle = "white";
      context.font = "bold 18px Arial";
      context.fillText("Text", (canvas.width/2) - 17, (canvas.height/2) + 8);
    </script>
  </body>
</html>

因此,我们使用 getElementById 方法访问了 <canvas> 元素,然后检索了 2D 上下文。
然后,我们使用 fillStyle 属性设置文本颜色,指定字体并使用 fillText 方法在 <canvas> 上添加我们的文本。

现在,让我们尝试一个使用 strokeText() 方法的示例。

使用 strokeText() 方法在 <canvas> 元素上添加文本的示例:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <style>
      #canvas {
        background: #59b8de;
      }
    </style>
  </head>
  <body>
    <canvas id="canvas" width="250" height="100"></canvas>
    <script>
      var canvas = document.getElementById("canvas");
      var context = canvas.getContext("2d");
      context.font = "30px Arial";
      context.strokeText("Text", 50, 50);
    </script>
  </body>
</html>
如何在 HTML5 <canvas> 元素上添加文本
日期:2020-06-02 22:14:54 来源:oir作者:oir