首頁 > web前端 > js教程 > 主體

如何使用 FabricJS 找到 Line 物件的真實中心座標?

王林
發布: 2023-09-16 12:09:03
轉載
1214 人瀏覽過

如何使用 FabricJS 找到 Line 对象的真实中心坐标?

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

語法

 getCenterPoint(): fabric.Point 
登入後複製

使用getCenterPoint 方法

範例

讓我們看一個程式碼範例,以查看getCenterPoint 方法運行時記錄的輸出用過的。 getCenterPoint 方法傳回物件的真實中心座標。在本例中,記錄的輸出為 x= 110.5 和 y= 150.5,它們是中心點。

<!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 getCenterPoint method</h2>
   <p>
      You can open console from dev tools and see that the logged output contains the center points
   </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([70, 100, 150, 200], {
         stroke: "blue",
      });
      
      // Add it to the canvas
      canvas.add(line);
      
      // Using the getCenterPoint method
      console.log(
         "The center point of Line object is: ",
         line.getCenterPoint()
      );
   </script>
</body>
</html>
登入後複製

使用getCenterPoint方法與不同的線的起始和結束座標

範例

在此範例中,我們使用了getCenterPoint i> 方法取得Line 實例的起始座標和結束座標為(100, 250) 和(250, 40) 時的中心座標。中心點是 175.5 和 145.5。

<!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 getCenterPoint method with different starting and ending coordinates of line
   </h2>
   <p>
      You can open console from dev tools and see that the logged output contains the center points
   </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([100, 250, 250, 40], {
         stroke: "blue",
      });
      
      // Add it to the canvas
      canvas.add(line);
      
      // Using the getCenterPoint method
      console.log(
         "The center point of Line object is: ",
         line.getCenterPoint()
      );
   </script>
</body>
</html>
登入後複製

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

來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!