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


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

語法

 getCoords(): Array 

使用 `getCoords` 方法

示例

讓我們看一個程式碼示例,看看使用 `getCoords` 方法時記錄的輸出。`getCoords` 方法以陣列格式返回線的左上、右上、右下和左下座標。

<!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>

更新於:2022年10月21日

701 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

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