如何使用 FabricJS 建立帶有邊框顏色的文字框?


在本文中,我們將學習如何使用 FabricJS 建立一個帶有邊框顏色的文字框。我們可以自定義、拉伸或移動文字框中的文字。我們還可以使用諸如fontSize、fontFamily、fontStyle、fontWeight 等屬性來自定義文字本身。為了建立一個文字框,我們必須建立一個fabric.Textbox 類的例項並將其新增到畫布中。FabricJS 提供的一個屬性是borderColor,它允許我們在物件處於活動狀態時操作邊框的顏色。

語法

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

引數

  • text − 此引數接受一個字串,即我們希望在文字框內顯示的文字字串。

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

選項鍵

  • borderColor − 此屬性接受一個字串,指定文字框物件被選中時的邊框顏色。其預設值為 rgb(178,204,255)。

示例 1

使用字串值傳遞 borderColor 鍵

讓我們來看一個程式碼示例,說明如何為borderColor 屬性賦值。我們將值“red”賦給borderColor 鍵,這有助於在選中文字框物件時建立紅色邊框。

<!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 borderColour key with a String value</h2>
   <p>You can select the textbox to see the red border colour</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("If you don’t love it, you’re going to fail.", {
         backgroundColor: "#b0e0e6",
         width: 400,
         top: 70,
         left: 110,
         angle: 15,
         borderColor: "red",
      });

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

示例 2

borderColor 鍵傳遞 RGBA 值

除了傳遞簡單的顏色名稱作為字串之外,我們還可以使用RGBA 值,其元件指定紅色、綠色、藍色和 Alpha 的數量,其中 Alpha 表示不透明度。在這個例子中,我們使用了rgb(164,0, 0),這是深紅色的 RGB 值。

<!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 an RGBA value to the borderColor key</h2>
   <p>You can select the textbox to see the border colour added using the rgba value</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("If you don’t love it, you’re going to fail.", {
         backgroundColor: "#b0e0e6",
         width: 400,
         top: 70,
         left: 110,
         angle: 15,
         borderColor: "rgb(164,0,0)",
      });

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

更新於:2022-07-29

741 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.