如何使用 FabricJS 更改 IText 的字体粗细?


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

然而,基于 IText 的文本框允许我们调整文本矩形的大小并自动换行。这对于 IText 来说并不适用,因为高度不会根据换行进行调整。我们可以使用各种属性来操作 IText 对象。字体粗细是指决定文本显示粗细的数值。我们可以使用 `fontWeight` 属性更改字体粗细。

语法

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

参数

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

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

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

选项键

  • fontWeight − 此属性接受一个数字字符串值,它决定了 IText 对象内文本的粗细。其默认值为 normal。

示例 1

将 fontWeight 属性作为键,并使用数值

让我们来看一个代码示例,了解当使用数值作为 fontWeight 属性的值时,IText 对象将如何显示。在本例中,我们将其值设置为 400,这意味着我们的文本将具有普通字体。我们也可以使用其他值,例如 600 或 800。

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>Passing the fontWeight property as key with a numerical value</h2> <p>You can see that the text is of normal font</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: 60, top: 70, fill: "#6abfe1", fontWeight: 400, } ); // Add it to the canvas canvas.add(itext); </script> </body> </html>

示例 2

将 fontWeight 属性作为键,并使用 “bold” 作为值

在这个例子中,我们将 fontWeight 属性作为键,其值为 “bold”。这意味着我们的 IText 对象将以粗体字呈现。

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>Passing the fontWeight property as key with the value as “bold”</h2> <p>You can see that the IText object has been rendered with bold text</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: 60, top: 70, fill: "#6abfe1", fontWeight: "bold", } ); // Add it to the canvas canvas.add(itext); </script> </body> </html>

更新于: 2022年9月12日

329 次浏览

开启您的职业生涯

完成课程获得认证

开始学习
广告