FabricJS – 如何將線條物件在繪製物件的堆疊中向下移動一步?


在本教程中,我們將學習如何使用 FabricJS 將線條物件在繪製物件的堆疊中向下移動一步。線條元素是 FabricJS 提供的基本元素之一。它用於建立直線。由於線條元素在幾何上是一維的並且不包含內部,因此它們永遠不會被填充。我們可以透過建立fabric.Line的例項,指定線條的 x 和 y 座標並將其新增到畫布上來建立線條物件。為了將線條物件在繪製物件的堆疊中向下移動一步,我們使用sendBackwards方法。

語法

 sendBackwards(intersecting: Boolean): fabric.Object 

引數

  • intersecting − 此引數接受一個布林值,當分配“true”值時,將物件傳送到下一個較低的相交物件的後面。如果為“false”值,則通常將物件傳送到堆疊中的下一個物件的後面。此引數是可選的。

使用sendBackwards方法

示例

讓我們看一個程式碼示例,以檢視使用sendBackwards方法時輸出。sendBackwards方法將物件在繪製物件的堆疊中向下移動一步。在本例中,使用sendBackwards方法後,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 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)的後面。

<!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 次檢視

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.