如何使用 FabricJS 建立一個在懸停於物件時顯示“禁止”游標的畫布?


在本文中,我們將使用 FabricJS 建立一個在懸停時顯示“禁止”游標的畫布。“禁止”是可用的原生游標樣式之一,也可以在 FabricJS 畫布中使用。FabricJS 提供各種型別的遊標,例如預設、全滾動、十字準星、列調整大小、行調整大小等,這些遊標在後臺重用原生遊標。`hoverCursor` 屬性設定懸停在畫布物件上時游標的樣式。

語法

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

引數

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

  • options (可選) − 此引數是一個物件,它為我們的畫布提供額外的自定義功能。使用此引數,可以更改與畫布相關的許多屬性,例如顏色、游標、邊框寬度等,其中 `hoverCursor` 是一個屬性,我們可以用它來設定在懸停在畫布物件上時的預設游標值。

示例 1

將 `hoverCursor` 鍵傳遞給類

hoverCursor 屬性接受一個字串,該字串確定在懸停在畫布物件上時要使用的游標名稱。讓我們來看一個程式碼示例,演示如何在 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>Canvas with not-allowed cursor on hover over object using FabricJS</h2>
   <p>Hover the mouse over the object to see how the cursor style changes.</p>
   <canvas id="canvas"></canvas>
   <script>
      // Initiate a canvas instance
      var canvas = new fabric.Canvas("canvas", {
         hoverCursor: "not-allowed",
      });
      // Creating an instance of the fabric.Circle class
      var cir = new fabric.Circle({
         radius: 40,
         fill: "#008b8b",
         left: 30,
         top: 20,
      });
      // Adding it to the canvas
      canvas.add(cir);
      canvas.setWidth(document.body.scrollWidth);
      canvas.setHeight(250);
   </script>
</body>
</html>

示例 2

使用點表示法設定 `hoverCursor`

在這個示例中,我們有一個矩形物件和一個橢圓物件,透過將 `hoverCursor` 屬性設定為“not-allowed”,當我們懸停在畫布中的任何物件上時,我們的游標將變為“禁止”游標型別。

<!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>Canvas with not-allowed cursor on hover over objects using FabricJS</h2>
   <p>There are two objects on this canvas. Hover the mouse over the objects to see how the cursor style changes.</p>
   <canvas id="canvas"></canvas>
   <script>
      // Initiate a canvas instance
      var canvas = new fabric.Canvas("canvas");
      canvas.hoverCursor = "not-allowed";
      // Creating an instance of the fabric.Rect class
      var rect = new fabric.Rect({
         left: 180,
         top: 80,
         width: 90,
         height: 150,
         fill: "#4169e1",
         angle: 82,
      });
      var ellipse = new fabric.Ellipse({
         top: 76,
         left: 210,
         fill: "#cd5b45",
         stroke: "#dcdcdc",
         strokeWidth: 1,
         rx: 30,
         ry: 50,
      });
      // Adding it to the canvas
      canvas.add(rect);
      canvas.add(ellipse);
      canvas.setWidth(document.body.scrollWidth);
      canvas.setHeight(250);
   </script>
</body>
</html>

更新於:2022年5月19日

瀏覽量:295

開啟你的職業生涯

完成課程獲得認證

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