如何使用 FabricJS 更改文本框的字体粗细?

fabricjshtml5 canvasjavascript

在本教程中,我们将了解如何使用 FabricJS 更改文本框的字体粗细。我们可以自定义、拉伸或移动文本框中写入的文本。为了创建文本框,我们必须创建 fabric.Textbox 类的实例并将其添加到画布中。字体粗细是指决定文本显示粗细程度的值。

语法

new fabric.Textbox(text: String, { fontWeight: Number|String }: Object)

参数

  • text − 此参数接受一个 String,即我们希望在文本框内显示的文本字符串。

  • options(可选)− 此参数是一个对象,可为文本框提供额外的自定义设置。使用此参数,可以更改与 fontWeight属性相关的对象的颜色、光标、笔触宽度等属性以及许多其他属性。

选项键

  • fontWeight − 此属性接受数字字符串值,该值决定文本在文本框中的显示粗细程度。其默认值为正常。

示例 1

 fontWeight属性作为带有数值的键传递

让我们看一个代码示例,以了解当fontWeight属性用作带有数值的键时我们的文本框对象将如何显示。在本例中,我们将值设置为 400,这意味着我们的文本将具有正常字体。我们也可以使用其他值,例如 600 或 800。

<!DOCTYPE html>
<html>
<head>
   <!-- Adding the Fabric JS Library-->
   <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/510/fabric.min.js"></script>
</head>
<body>
   <h2>Passing the fontWeight property as key with a numerical value</h2>
   <p>You can see that the text is of normal font</p>
   <canvas id="canvas"></canvas>
   <script>
      // 启动一个canvas实例
      var canvas = new fabric.Canvas("canvas");
      canvas.setWidth(document.body.scrollWidth);
      canvas.setHeight(250);

      // 初始化一个 textbox 文本框对象
      var textbox = new fabric.Textbox("Solitary trees, if they grow at all, grow strong.", {
         backgroundColor: "#fff8dc",
         width: 400,
         left: 50,
         top: 70,
         fill: "#cf3476",
         fontWeight: 400,
      });

      // 将其添加到画布
      canvas.add(textbox);
   </script>
</body>
</html>

示例 2

fontWeight 属性作为键传递,值为 “bold”

在此示例中,我们将 fontWeight  属性作为键传递,值为 “bold”。这意味着我们的文本框对象将呈现带有较粗字母的文本。

<!DOCTYPE html>
<html>
<head>
   <!-- Adding the Fabric JS Library-->
   <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/510/fabric.min.js"></script>
</head>
<body>
   <h2>Passing the fontWeight property as key with the value as “bold”</h2>
   <p>You can see that the textbox object has been rendered with bold text</p>
   <canvas id="canvas"></canvas>
   <script>
      // 启动一个canvas实例
      var canvas = new fabric.Canvas("canvas");
      canvas.setWidth(document.body.scrollWidth);
      canvas.setHeight(250);

      // 初始化一个 textbox 文本框对象
      var textbox = new fabric.Textbox("Solitary trees, if they grow at all, grow strong", {
         backgroundColor: "#fff8dc",
         width: 400,
         left: 50,
         top: 70,
         fill: "#cf3476",
         fontWeight: "bold",
      });

      // 将其添加到画布
      canvas.add(textbox);
   </script>
</body>
</html>

相关文章