FabricJS – 如何獲取線條物件以不同原點為基準的座標?


在本教程中,我們將學習如何使用 FabricJS 獲取線條物件的座標,就好像它具有不同的原點一樣。線條元素是 FabricJS 提供的基本元素之一。它用於建立直線。由於線條元素在幾何上是一維的並且不包含內部,因此它們永遠不會填充。我們可以透過建立 fabric.Line 的例項,指定線條的 x 和 y 座標並將其新增到畫布上來建立線條物件。為了找到線條物件以不同原點為基準的座標,我們使用 getPointByOrigin 方法。

語法

 getPointByOrigin(originX: String, originY: String): fabric.Point 

引數

  • originX − 此引數接受一個字串,用於指定水平原點。可能的值為“left”、“center”或“right”。

  • originY − 此引數接受一個字串,用於指定垂直原點。可能的值為“top”、“center”或“bottom”。

使用 getPointByOrigin 方法

示例

讓我們看一個程式碼示例,以檢視使用 getPointByOrigin 方法時記錄的輸出。getPointByOrigin 方法返回使用者指定原點物件的座標。在本例中,我們也使用了 getCenterPoint 方法,以便您可以看到給定線條物件的真實中心點。而在使用 getPointByOrigin 方法時,我們以左下角為原點,因此記錄的輸出為 x= 100 和 y= 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 getPointByOrigin method</h2> <p> You can open console from dev tools and see that the logged output contains the coordinates </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 getCenterPoint method console.log( "The real center point of the object is: ", line.getCenterPoint() ); // Using getPointByOrigin method console.log( "The coordinates returned while using getPointByOrigin method are: ", line.getPointByOrigin("left", "bottom") ); </script> </body> </html>

使用 getPointByOrigin 方法和不同的值

示例

在此示例中,我們使用了 getPointByOrigin 方法來獲取線條物件的座標,其中水平和垂直中心點分別為“right”和“top”。這意味著右上角將被視為中心。

<!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 getPointByOrigin method with different values</h2> <p> You can open console from dev tools and see that the logged output contains the coordinates </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 getPointByOrigin method console.log( "The coordinates returned while using getPointByOrigin method are: ", line.getPointByOrigin("right", "top") ); </script> </body> </html>

更新於: 2022年10月20日

302 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.