如何使用 FabricJS 更改文本框的字体样式?


在本教程中,我们将学习如何使用 FabricJS 更改文本框的字体样式。我们可以自定义、拉伸或移动文本框中的文字。要创建文本框,我们需要创建一个 `fabric.Textbox` 类的实例并将其添加到画布中。字体样式指的是在文本框中输入字符的样式。

语法

new fabric.Textbox(text: String, { fontStyle: String }: Object)

参数

  • text − 此参数接受一个字符串,即我们想要在文本框中显示的文本字符串。

  • options (可选) − 此参数是一个对象,它为我们的文本框提供额外的自定义选项。使用此参数,可以更改与对象相关的许多属性,其中 `fontStyle` 是一个属性,例如颜色、光标、描边宽度等等。

选项键

  • fontStyle − 此属性接受一个字符串,允许我们设置文本框内文本的字体变体。可能的值为“normal”、“italic”和“oblique”,如下所述:

    • normal − 文本显示正常的字体样式。这也是默认值。

    • italic − 文本显示为斜体,向右倾斜。

    • oblique − 文本显示为正常字体的倾斜版本。它通常看起来类似于斜体,但斜体是字体的特殊版本,而倾斜版本只是稍微倾斜的常规版本。

示例 1

将 `fontStyle` 属性作为键,值为“oblique”

让我们看一个代码示例,了解当 `fontStyle` 属性用作键且值为“oblique”时,我们的文本框对象将如何显示。

<!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 fontStyle property as key with the value as "oblique"</h2>
   <p>You can see that the text is oblique</p>
   <canvas id="canvas"></canvas>
   <script>
      // Initiate a canvas instance
      var canvas = new fabric.Canvas("canvas");
      canvas.setWidth(document.body.scrollWidth);
      canvas.setHeight(250);

      // Initiate a textbox object
      var textbox = new fabric.Textbox("Good things happen to those who hustle.", {
         backgroundColor: "#fff8dc",
         width: 400,
         left: 50,
         top: 70,
         fill: "#cf3476",
         fontStyle: "oblique",
      });

      // Add it to the canvas
      canvas.add(textbox);
   </script>
</body>
</html>

示例 2

将 `fontStyle` 属性作为键,值为“italic”

在这个例子中,我们将 `fontStyle` 属性作为键,值为“italic”。这意味着我们的文本框对象将呈现为向右倾斜的文本。

<!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 fontStyle property as key with the value as "italic"</h2>
   <p>You can see that the text is italic</p>
   <canvas id="canvas"></canvas>
   <script>
      // Initiate a canvas instance
      var canvas = new fabric.Canvas("canvas");
      canvas.setWidth(document.body.scrollWidth);
      canvas.setHeight(250);

      // Initiate a textbox object
      var textbox = new fabric.Textbox("Good things happen to those who hustle.", {
         backgroundColor: "#fff8dc",
         width: 400,
         left: 50,
         top: 70,
         fill: "#cf3476",
         fontStyle: "italic",
      });

      // Add it to the canvas
      canvas.add(textbox);
   </script>
</body>
</html>

更新于:2022年7月29日

748 次浏览

开启您的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.