如何在 FabricJS 中为 IText 添加下划线?


在本教程中,我们将学习如何使用 FabricJS 为 IText 添加下划线。IText 类在 FabricJS 1.4 版本中引入,扩展了 fabric.Text,用于创建 IText 实例。IText 实例使我们能够自由地选择、剪切、粘贴或添加新文本,无需额外的配置。它还支持各种快捷键和鼠标/触摸组合,使文本具有交互性,而这些在 Text 中并没有提供。

然而,基于 IText 的文本框允许我们调整文本矩形的大小并自动换行。这对于 IText 来说并不适用,因为高度不会根据换行进行调整。我们可以使用各种属性来操作 IText 对象。同样,我们也可以使用 underline 属性为 IText 对象添加下划线。

语法

new fabric.IText(text: String , { underline: Boolean }: Object)

参数

  • text − 此参数接受一个字符串,即我们要显示的文本字符串。

  • options (可选) − 此参数是一个对象,它为我们的 IText 对象提供了额外的自定义功能。使用此参数,可以更改与对象相关的许多属性,例如颜色、光标、边框宽度以及下划线。

选项键

  • underline − 此属性接受一个布尔值,允许我们为文本添加下划线。

示例 1

IText 对象的默认外观

让我们来看一个代码示例,看看当不使用 underline 属性时,IText 对象是什么样的。在这种情况下,没有文本修饰下划线。

<!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>Default appearance of the IText object</h2> <p>You can see that no text decoration underline is present</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 itext = new fabric.IText( "Add sample text here.
Lorem ipsum dolor sit amet"
,{ width: 300, left: 50, top: 70, fill: "#d755da", textBackgroundColor: "black", } ); // Add it to the canvas canvas.add(itext); </script> </body> </html>

示例 2

将 underline 属性作为键,值为 true

在这个例子中,我们将看到如何使用 underline 属性添加文本修饰下划线。underline 属性接受布尔值,因此我们传递了一个 true 值,这将为我们的文本添加下划线。

<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>Passing the underline property as key with a true value</h2> <p>You can see that text decoration underline is present</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 itext = new fabric.IText( "Add sample text here.
Lorem ipsum dolor sit amet"
,{ width: 300, left: 50, top: 70, fill: "#d755da", textBackgroundColor: "black", underline: true, } ); // Add it to the canvas canvas.add(itext); </script> </body> </html>

更新于:2022年9月12日

283 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.