如何在使用 FabricJS 的 IText 中將物件移動到已繪製物件的堆疊頂部?


在本教程中,我們將學習如何在使用 FabricJS 的 IText 中將物件移動到已繪製物件的堆疊頂部。IText 類是在 FabricJS 1.4 版本中引入的,它擴充套件了 fabric.Text 並用於建立 IText 例項。IText 例項使我們可以自由地選擇、剪下、貼上或新增新文字,而無需額外的配置。它還支援各種按鍵組合和滑鼠/觸控組合,使文字具有互動性,而這些功能在 Text 中並未提供。

然而,基於 IText 的文字框允許我們調整文字矩形的尺寸並自動換行。這對於 IText 來說並不適用,因為高度不會根據換行進行調整。我們可以使用各種屬性來操作 IText 物件。同樣,我們可以使用 bringToFront 方法將物件移動到已繪製物件的堆疊頂部。

語法

bringToFront(): fabric.Object

示例 1

不使用 bringToFront 方法

讓我們來看一個程式碼示例,看看在不使用 bringToFront 方法時 IText 物件的行為。在本例中,我們初始化了兩個 IText 物件,即 itext1 和 itext2。您可以注意到,第二個文字覆蓋了第一個文字,將其隱藏在後面。

<!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>Without using the bringToFront method</h2> <p> You can see that the first itext object is hidden behind the second itext object </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 an itext object var itext1 = new fabric.IText("First itext object.", { width: 300, left: 110, top: 70, fill: "#b666d2", fontStyle: "bold", backgroundColor: "#f8f4ff", }); // Initiate another itext object var itext2 = new fabric.IText("Second itext object.", { width: 300, left: 130, top: 90, fill: "white", backgroundColor: "#c8a2c8", }); // Add it to the canvas canvas.add(itext1); canvas.add(itext2); </script> </body> </html>

示例 2

使用 bringToFront 方法

讓我們來看一個程式碼示例,看看在使用 bringToFront 方法時 IText 物件的行為。在本例中,我們的 itext1 物件現在將位於堆疊頂部,因此它將不再隱藏在 itext2 後面。

<!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 the bringToFront method</h2> <p> You can see that the first itext object is no longer hidden behind the second itext object </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 an itext object var itext1 = new fabric.IText("First itext object.", { width: 300, left: 110, top: 70, fill: "#b666d2", fontStyle: "bold", backgroundColor: "#f8f4ff", }); // Initiate another itext object var itext2 = new fabric.IText("Second itext object.", { width: 300, left: 130, top: 90, fill: "white", backgroundColor: "#c8a2c8", }); // Add it to the canvas canvas.add(itext1); canvas.add(itext2); // Using the bringToFront method itext1.bringToFront(); </script> </body> </html>

更新於:2022年9月13日

736 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

開始學習
廣告