在本教程中,我们将学习如何使用 FabricJS 获取线的坐标,就好像它具有不同的原点一样。Line 元素是 FabricJS 中提供的基本元素之一。它用于创建直线。因为线元素在几何上是一维的并且不包含内部,所以它们永远不会被填充。我们可以通过创建fabric.Line的实例来创建线条对象,指定线条的 x 和 y 坐标并将其添加到画布。为了找到 Line 对象的坐标,就好像它具有不同的原点一样,我们使用getPointByOrigin方法。
getPointByOrigin(originX: String, originY: String):fabric.Point
originX - 此参数接受指定水平原点的字符串。可能的值为“左”、“中心”或“右”。
originY - 此参数接受表示垂直原点的字符串。可能的值为“顶部”、“中心”或“底部”。
让我们看一个代码示例,以查看使用getPointByOrigin方法时记录的输出。getPointByOrigin方法返回用户指定原点的对象坐标。在这种情况下,我们也使用了getCenterPoint方法,以便您可以看到给定 Line 对象的真实中心点。而在使用getPointByOrigin方法时,我们将左下角的点作为原点,因此记录的输出是 x= 100 和 y= 120。
<!DOCTYPE html> <html> <head> <!-- Adding the Fabric JS Library--> <script xx_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> //启动画布实例 var canvas = new fabric.Canvas("canvas"); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); //启动一个 Line 对象 var line = new fabric.Line([200, 100, 100, 40], { stroke: "blue", strokeWidth: 20, }); //将其添加到画布 canvas.add(line); //使用 getCenterPoint 方法 console.log( "The real center point of the object is: ", line.getCenterPoint() ); //使用 getPointByOrigin 方法 console.log( "The coordinates returned while using getPointByOrigin method are: ", line.getPointByOrigin("left", "bottom") ); </script> </body> </html>
在这个例子中,我们使用了getPointByOrigin方法来获取Line对象在水平和垂直中心点分别为'right'和'top'时的坐标。这意味着右上角的点将被视为中心。
<!DOCTYPE html> <html> <head> <!-- Adding the Fabric JS Library--> <script xx_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> //启动画布实例 var canvas = new fabric.Canvas("canvas"); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); //启动一个 Line 对象 var line = new fabric.Line([200, 100, 100, 40], { stroke: "blue", strokeWidth: 20, }); //将其添加到画布 canvas.add(line); //使用 getPointByOrigin 方法 console.log( "The coordinates returned while using getPointByOrigin method are: ", line.getPointByOrigin("right", "top") ); </script> </body> </html>