如何使用 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.