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、line2line3。儘管它們已按照其數字順序新增到畫布中,但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>

更新於:2022年10月25日

325 次瀏覽

開啟您的職業生涯

完成課程獲得認證

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