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


在本教程中,我们将演示如何使用 FabricJS 获取 Line 对象的坐标。Line 元素是 FabricJS 提供的基本元素之一,用于创建直线。由于线元素在几何上是一维的,并且不包含内部,因此它们永远不会被填充。我们可以通过创建 `fabric.Line` 的实例,指定线的 x 和 y 坐标,并将其添加到画布上来创建线对象。为了获取 Line 对象的坐标,我们使用 `getCoords` 方法。

语法

 getCoords(): Array 

使用 `getCoords` 方法

示例

让我们看一个代码示例,看看使用 `getCoords` 方法时记录的输出。`getCoords` 方法以数组格式返回线的左上、右上、右下和左下坐标。

Open Compiler
<!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),它们分别是线的左上、右上、右下和左下坐标。

Open Compiler
<!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 次浏览

启动您的职业生涯

通过完成课程获得认证

开始学习
广告