如何使用 FabricJS 更改文字框的字型大小?


在本教程中,我們將瞭解如何使用 FabricJS 更改文字框的字型大小。我們可以自定義、拉伸或移動文字框中的文字。為了建立文字框,我們必須建立 fabric.Textbox 類的例項並將其新增到畫布中。字型大小指定文字框中顯示的字元的大小。我們可以使用 fontSize 屬性更改字型大小。

語法

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

引數

  • text − 此引數接受一個字串,它是我們想要在文字框內顯示的文字字串。

  • options(可選)− 此引數是一個物件,它為我們的文字框提供額外的自定義。使用此引數可以更改與物件相關的顏色、游標、筆劃寬度和許多其他屬性,其中fontSize 是一個屬性。

選項鍵

  • fontSize − 此屬性接受一個數字,它允許我們設定文字框內文字的大小。其預設值為 40。

示例 1

文字框物件的預設外觀

讓我們來看一個程式碼示例,以瞭解當不使用fontSize 屬性時,我們的文字框物件將如何顯示。

<!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>Default appearance of the Textbox object</h2>
   <p>You can see the default value of text in a textbox which is 40</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("Impossible is for the unwilling.", {
         backgroundColor: "#e6e8fa",
         width: 400,
         left: 100,
         top: 70,
         fill: "#000060",
      });

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

示例 2

fontSize 屬性作為鍵傳遞,並使用自定義值

在此示例中,我們將fontSize 屬性作為鍵傳遞,其值為 30。這意味著我們的文字框物件現在將呈現字型大小為 30px 的文字。

<!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 fontSize property as key with a custom value</h2>
   <p>You can see the font size is 30 now which is slightly smaller than the default</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("Impossible is for the unwilling.", {
         backgroundColor: "#e6e8fa",
         width: 400,
         left: 100,
         top: 70,
         fill: "#000060",
         fontSize: 30,
      });

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

更新於: 2022-07-29

560 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.