FabricJS – 如何将线条对象移动到绘制对象的堆栈底部?
在本教程中,我们将学习如何使用 FabricJS 将线条对象移动到绘制对象的堆栈底部。线条元素是 FabricJS 提供的基本元素之一。它用于创建直线。因为线条元素在几何上是一维的并且不包含内部,所以它们永远不会被填充。我们可以通过创建一个fabric.Line的实例,指定线条的x和y坐标并将其添加到画布上来创建一个线条对象。为了将线条对象移动到绘制对象的堆栈底部,我们使用sendToBack方法。
语法
sendToBack(): fabric.Object
使用sendToBack方法
示例
让我们看一个代码示例,看看使用sendToBack方法时的输出。sendToBack方法将对象移动到绘制对象堆栈的底部。在这种情况下,使用sendToBack方法后,line2被发送到line1的后面。
<!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 sendToBack method</h2> <p>You can see that line2 (red) lies behind line1 (blue)</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 sendToBack method line2.sendToBack(); </script> </body> </html>
使用三个对象的方法sendToBack
示例
在这个例子中,我们使用了三个线条对象,即line1、line2和line3。尽管它们已按照其数字顺序添加到画布中,但line3显然位于最后。这是因为我们使用了sendToBack方法,该方法将line3发送到绘制对象堆栈的底部。
<!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 sendToBack method with three objects</h2> <p> You can see that line3 (green) lies at the bottom of 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, }); // 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 sendToBack method line3.sendToBack(); </script> </body> </html>
广告