如何在 FabricJS 中為文字框新增陰影?


在本教程中,我們將學習如何使用 FabricJS 為文字框新增陰影。我們可以自定義、拉伸或移動文字框中的文字。為了建立文字框,我們必須建立一個 `fabric.Textbox` 類的例項並將其新增到畫布上。我們的文字框物件可以透過多種方式進行自定義,例如更改其尺寸、新增背景顏色,甚至新增陰影。我們可以使用 `shadow` 屬性為文字框新增陰影。

語法

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

引數

  • text − 此引數接受一個字串,即我們想要在文字框中顯示的文字字串

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

選項鍵

  • shadow − 此屬性接受一個fabric.Shadow 物件,允許我們為文字框物件新增陰影。例如,為了向文字框物件新增陰影,我們需要建立一個新的 `fabric.Shadow` 例項,然後將該例項賦值給 `shadow` 屬性。

示例 1

將陰影物件傳遞給 `shadow` 屬性

讓我們來看一個程式碼示例,瞭解如何為 `shadow` 屬性賦值,以便為文字框物件新增陰影。首先,我們需要建立一個新的 **fabric.Shadow** 例項,然後將其賦值給我們的 `shadow` 屬性。

<!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 shadow object to the shadow property</h2>
   <p>You can see that a blue shadow has been added to the textbox</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 shadow instance
      var shadow = new fabric.Shadow({
         color: "blue",
         blur: 20,
      });

      // Initiate a textbox object
      var textbox = new fabric.Textbox("Try Again. Fail again. Fail better.", {
         backgroundColor: "#fffff0",
         width: 400,
         left: 110,
         top: 70,
         fill: "violet",
         strokeWidth: 2,
         stroke: "blue",
         textAlign: "center",
         shadow: shadow,
      });

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

示例 2

將 RGBA 值傳遞給陰影物件

我們還可以調整陰影並使其具有模糊外觀,方法是為其分配一個 RGBA 值,它代表紅色、綠色、藍色和 alpha 值。Alpha 值決定顏色的不透明度。

<!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 shadow object</h2>
   <p>You can see the shadow created using RGBA colour 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 shadow instance
      var shadow = new fabric.Shadow({
         color: "rgba(0,0,205, 0.7)",
         blur: 20,
      });

      // Initiate a textbox object
      var textbox = new fabric.Textbox("Try Again. Fail again. Fail better.", {
         backgroundColor: "#fffff0",
         width: 400,
         left: 110,
         top: 70,
         fill: "violet",
         strokeWidth: 2,
         stroke: "blue",
         textAlign: "center",
         shadow: shadow,
      });

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

更新於:2022年7月29日

594 次瀏覽

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告