首頁  >  文章  >  web前端  >  如何使用 FabricJS 取得 Line 物件的座標?

如何使用 FabricJS 取得 Line 物件的座標?

WBOY
WBOY轉載
2023-09-22 17:45:091526瀏覽

如何使用 FabricJS 获取 Line 对象的坐标?

在本教學中,我們將展示如何使用 FabricJS 取得線的座標。 Line 元素是 FabricJS 中提供的基本元素之一。它用於創建直線。由於線元素在幾何上是一維的並且不包含內部,因此它們永遠不會被填充。我們可以透過建立 fabric.Line 的實例來建立線條對象,指定線條的 x 和 y 座標並將其新增至畫布。為了取得 Line 物件的座標,我們使用 getCoords 方法。

語法

 getCoords(): Array 

使用getCoords 方法

範例

讓我們看一個程式碼範例,以查看getCoords 方法執行時記錄的輸出用過的。 getCoords 方法以陣列格式傳回 Line 的左上角、右上角、右下角和左下角座標。

<!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>Using getCoords method</h2>
   <p>You can open console from dev tools and see the logged output</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 Line object
      var line = new fabric.Line([50, 100, 310, 100], {
         stroke: "blue",
         strokeWidth: 10,
      });
      
      // Add it to the canvas
      canvas.add(line);
      
      // Using getCoords method
      console.log("The coordinates are: ", line.getCoords());
   </script>
</body>
</html>

使用getCoords 方法繪製斜線

範例

在此範例中,我們使用了getCoords 方法取得具有不同起始和結束座標的Line 實例的座標。我們可以看到記錄的輸出是:(100, 40)、(220, 40)、(220,120)、(100,120),分別是該行的左上角、右上角、右下角和左下角座標.

<!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>Using getCoords method for a slant line</h2>
   <p>You can open console from dev tools and see the logged output</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 Line object
      var line = new fabric.Line([200, 100, 100, 40], {
         stroke: "blue",
         strokeWidth: 20
      });
      
      // Add it to the canvas
      canvas.add(line);
      
      // Using getCoords method
      console.log("The coordinates are: ", line.getCoords());
   </script>
</body>
</html>

以上是如何使用 FabricJS 取得 Line 物件的座標?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除