如何在 FabricJS 中为 IText 对象的多行文本添加行高?


在本教程中,我们将学习如何在 FabricJS 中使用 IText 对象为多行文本添加行高。IText 类在 FabricJS 1.4 版本中引入,扩展了 fabric.Text,用于创建 IText 实例。IText 实例使我们可以自由地选择、剪切、粘贴或添加新文本,无需额外的配置。

还支持各种键盘组合和鼠标/触摸组合,使文本具有交互性,而 Text 中并未提供这些功能。然而,基于 IText 的 Textbox 允许我们调整文本矩形的尺寸并自动换行。这对于 IText 不适用,因为高度不会根据换行进行调整。我们可以使用各种属性来操作 IText 对象。同样,我们可以使用 lineHeight 属性来增加行之间的额外高度。

语法

new fabric.IText(text: String, { lineHeight: Number }: Object)

参数

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

  • options (可选) − 此参数是一个对象,它为我们的 IText 对象提供额外的自定义选项。使用此参数可以更改与对象相关的颜色、光标、边框宽度以及许多其他属性,lineHeight 属性也是其中之一。

选项键

  • lineHeight − 此属性接受一个数字,允许我们控制每行之间的间距。lineHeight 属性的默认值为 1.16。

示例 1

IText 对象的默认外观

让我们看一个代码示例,了解 IText 对象在 lineHeight 属性的默认值下的外观。在本例中,我们不会像下面那样将任何 lineHeight 键传递给类:

<!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 IText object</h2> <p>You can see the default line height in this example</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: 210, top: 70, fill: "green", } ); // Add it to the canvas canvas.add(itext); </script> </body> </html>

示例 2

将 lineHeight 属性作为键传递

在本例中,我们将看到为 lineHeight 属性赋值如何改变 IText 对象中每行之间的间距。这里我们使用了 2 作为 lineHeight,从而增加了每行之间的间距。

<!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 lineHeight property as key</h2> <p>You can see our IText object now has a line height of 2</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: 210, top: 70, fill: "green", lineHeight: 2, } ); // Add it to the canvas canvas.add(itext); </script> </body> </html>

更新于: 2022年9月12日

461 次浏览

启动你的职业生涯

完成课程获得认证

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