如何使用 FabricJS 設定畫布上選擇區域的邊框顏色?


在本文中,我們將學習如何使用 FabricJS 設定畫布上選擇區域的邊框顏色。選擇指示是否應啟用組選擇。FabricJS 允許我們使用 selectionBorderColor 屬性相應地調整邊框顏色。

語法

new fabric.Canvas(element: HTMLElement|String, { selectionBorderColor: String }: Object)

引數

  • element − 此引數是<canvas> 元素本身,可以使用 document.getElementById() 或<canvas> 元素本身的 ID 獲取。FabricJS 畫布將在此元素上初始化。

  • options (可選) − 此引數是一個物件,它為我們的畫布提供額外的自定義。使用此引數,可以更改與畫布相關的許多屬性,例如顏色、游標、邊框寬度等,其中 selectionBorderColor 屬性用於指示選擇邊框的顏色。selectionBorderColor 屬性的預設值為 rgba(255,255,255,0.3)。

示例 1

使用顏色名稱設定選擇區域顏色

selectionBorderColor 屬性接受一個字串,該字串決定選擇邊框的顏色。此顏色通常比選擇本身的顏色更深。讓我們看看如何使用 FabricJS 設定畫布中選擇區域邊框顏色的程式碼示例。

<!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>Setting the border color of a selection area on a canvas</h2>
   <p>Select an area around the object. You will notice that the border color of the selection would be red in color. </p>
   <canvas id="canvas"></canvas>
   <script>
      // Initiate a canvas instance
      var canvas = new fabric.Canvas("canvas", {
         selectionBorderColor: "green",
      });
      // Creating an instance of the fabric.Rect class
      var rect = new fabric.Rect({
         left: 170,
         top: 90,
         width: 60,
         height: 80,
         fill: "#006400",
         angle: 90,
      });
      // Adding it to the canvas
      canvas.add(rect);
      canvas.setWidth(document.body.scrollWidth);
      canvas.setHeight(250);
   </script>
</body>
</html>

示例 2

使用 rgba 值設定選擇區域顏色

我們還可以使用“rgba”值,其中“a”代表“alpha”,表示不透明度。在此示例中,我們使用了酒紅色,其“rgba”值為 (112,0,0),0.9 表示不透明度。

<!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>Setting border colour of selection area using FabricJs</h2>
   <p>Select an area around the object to see the border color of the selection area. Here we have used "rgba" value to set the border color of the selection area.</p>
   <canvas id="canvas"></canvas>
   <script>
      // Initiate a canvas instance
      var canvas = new fabric.Canvas("canvas", {
         selectionBorderColor: "rgba(112,0,0,0.9)",
      });
      // Creating an instance of the fabric.Rect class
      var rect = new fabric.Rect({
         left: 170,
         top: 90,
         width: 60,
         height: 80,
         fill: "#006400",
         angle: 90,
      });
      // Adding it to the canvas
      canvas.add(rect);
      canvas.setWidth(document.body.scrollWidth);
      canvas.setHeight(250);
   </script>
</body>
</html>

更新於:2022年5月19日

722 次瀏覽

啟動您的職業生涯

完成課程獲得認證

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