如何使用 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 wait cursor on hover over objects using FabricJS</h2>
   <p>Hover the mouse over the circle to see how the cursor style changes.</p>
   <canvas id="canvas"></canvas>
   <script>
      // Initiate a canvas instance
      var canvas = new fabric.Canvas("canvas", {
         hoverCursor: "wait",
      });
      // Creating an instance of the fabric.Circle class
      var cir = new fabric.Circle({
         radius: 60,
         fill: "#f4a460",
         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 賦值為“wait”,當我們懸停在畫布上的任何物件上時,我們的游標將變為等待游標型別。

<!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 wait cursor on hover over objects using FabricJS</h2>
   <p>Hover the mouse over the rectangle 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 = "wait";
      // Creating an instance of the fabric.Rect class
      var rect = new fabric.Rect({
         left: 190,
         top: 80,
         width: 90,
         height: 150,
         fill: "#9f8170",
         angle: 30,
      });
      // Adding it to the canvas
      canvas.add(rect);
      canvas.setWidth(document.body.scrollWidth);
      canvas.setHeight(250);
   </script>
</body>
</html>

更新於:2022年5月19日

164 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

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