FabricJS – 如何將線條物件移動到已繪製物件堆疊中的特定索引?


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

語法

moveTo(index: Number): fabric.Object

引數

  • index − 此引數接受一個數字值,該值指定我們想要在已繪製物件堆疊中移動物件的級別。

使用moveTo方法

示例

讓我們來看一個程式碼示例,看看使用moveTo方法時的輸出。moveTo方法將物件移動到已繪製物件堆疊中的指定級別。在本例中,使用moveTo方法將line2傳送到第0個索引。

<!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 moveTo method</h2> <p> You can see that line2 (red) has been moved to the 0th index 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 moveTo method line2.moveTo(0); </script> </body> </html>

使用三個物件的moveTo方法

示例

在這個例子中,我們使用了三個線條物件,分別是line1、line2line3。雖然它們是根據它們的數字順序新增到畫布中的,但line3顯然位於line2之後,位於第一個索引。這是因為我們使用了moveTo方法,該方法將line3傳送到第一個索引,而line1line2分別佔據已繪製物件堆疊中的第0個和第2個索引。

<!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 moveTo method with three objects</h2> <p> You can see that line3 (green) lies in the 1st index which is middle position in stack </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 moveTo method line3.moveTo(1); </script> </body> </html>

更新於:2022年10月25日

794 次瀏覽

開啟您的職業生涯

透過完成課程獲得認證

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