如何在使用 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。您可以注意到,第二个文本覆盖了第一个文本,将其隐藏在后面。

Open Compiler
<!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>

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

示例 2

使用 bringToFront 方法

让我们来看一个代码示例,看看在使用 bringToFront 方法时 IText 对象的行为。在本例中,我们的 itext1 对象现在将位于堆栈顶部,因此它将不再隐藏在 itext2 后面。

Open Compiler
<!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 次浏览

启动您的职业生涯

通过完成课程获得认证

开始学习
广告