FabricJS – 如何将线条对象在绘制对象的堆栈中向下移动一步?


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

语法

 sendBackwards(intersecting: Boolean): fabric.Object 

参数

  • intersecting − 此参数接受一个布尔值,当分配“true”值时,将对象发送到下一个较低的相交对象的后面。如果为“false”值,则通常将对象发送到堆栈中的下一个对象的后面。此参数是可选的。

使用sendBackwards方法

示例

让我们看一个代码示例,以查看使用sendBackwards方法时输出。sendBackwards方法将对象在绘制对象的堆栈中向下移动一步。在本例中,使用sendBackwards方法后,line2 发送到 line1 后面。

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 sendBackwards method</h2> <p> You can see that line2 (red) has been moved down in the stack of drawn objects </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 line1 = new fabric.Line([200, 100, 100, 40], { stroke: "blue", strokeWidth: 20, }); // Initiate another Line object var line2 = new fabric.Line([200, 70, 70, 40], { stroke: "red", strokeWidth: 20, }); // Add both to the canvas canvas.add(line1); canvas.add(line2); // Using sendBackwards method line2.sendBackwards(); </script> </body> </html>

使用sendBackwards方法和三个对象以及启用交叉键

示例

在此示例中,我们使用了三个线条对象,即line1、line2line3。尽管它们已根据其数字顺序添加到画布中,但line3显然位于line1后面。这是因为我们使用了启用交叉键的sendBackwards方法,该方法将line3发送到其下一个较低的相交对象(即line1)的后面。

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 sendBackwards method with three objects and intersection key enabled</h2> <p> You can see that the green line now lies behind the blue line which is line number 1 </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 line1 = new fabric.Line([200, 100, 100, 40], { stroke: "blue", strokeWidth: 20, }); // Initiate another Line object var line2 = new fabric.Line([500, 70, 400, 40], { stroke: "red", strokeWidth: 20, }); // Initiate another Line object var line3 = new fabric.Line([200, 30, 30, 90], { stroke: "green", strokeWidth: 20, }); // Add them all to the canvas canvas.add(line1); canvas.add(line2); canvas.add(line3); // Using sendBackwards method line3.sendBackwards(true); </script> </body> </html>

更新于: 2022年10月20日

198 次查看

启动您的 职业生涯

通过完成课程获得认证

开始学习
广告