在本教程中,我們將學習如何使用 FabricJS 將 Line 物件移到繪製物件堆疊的頂部。 Line 元素是 FabricJS 中提供的基本元素之一。它用於創建直線。由於線元素在幾何上是一維的並且不包含內部,因此它們永遠不會被填充。我們可以透過建立 fabric.Line 實例來建立線條對象,指定線條的 x 和 y 座標並將其新增至畫布。為了將 Line 物件移到繪製物件堆疊的頂部,我們使用 bringToFront 方法。
bringToFront(): fabric.Object
讓我們來看一個程式碼範例,看看使用 bringToFront 方法時的輸出。 bringToFront 方法將物件移到繪製物件堆疊的頂部。在本例中,使用 bringToFront 方法將 line1 移到 line2 之上。
<!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 bringToFront method</h2> <p>You can see that line1 (blue) lies above line2 (red)</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 bringToFront method line1.bringToFront(); </script> </body> </html>
在此範例中,我們使用了三個線條對象,分別是 line1、line2 和 line3。儘管它們已根據數字順序添加到畫布中,但 line1 顯然位於最頂部。這是因為我們使用了 bringToFront 方法,該方法將 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 bringToFront method with three objects</h2> <p> You can see that line1 (blue) lies at the top 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 bringToFront method line1.bringToFront(); </script> </body> </html>
以上是FabricJS – 如何將 Line 物件移到繪製物件堆疊的頂部?的詳細內容。更多資訊請關注PHP中文網其他相關文章!