如何在 FabricJS 中设置 IText 的路径侧?


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

然而,基于 IText 的文本框允许我们调整文本矩形的尺寸并自动换行。这对于 IText 来说是不正确的,因为高度不会根据换行进行调整。我们可以使用各种属性来操作 IText 对象。同样,我们可以使用 pathSide 属性为文本指定路径侧。

语法

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

参数

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

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

选项键

  • pathSide − 此属性接受一个字符串值,允许我们指定应在路径的哪一侧绘制文本。默认值为“left”。

示例 1

使用默认值传递 pathSide 属性作为键

让我们来看一个代码示例,看看当 pathSide 属性使用其默认值时 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>Passing the pathSide property as key with its default value</h2> <p>You can see that the text is drawn on the left side of the path</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 a path instance var path = new fabric.Path("M 0 0 C 100 -100 150 -100 300 0", { strokeWidth: 1, stroke: "blue", fill: "white", strokeWidth: 4, }); // Initiate an itext object var itext = new fabric.IText("Add sample text here.", { width: 300, left: 110, top: 70, fill: "red", path: path, pathSide: "left", }); // Add it to the canvas canvas.add(itext); </script> </body> </html>

示例 2

使用不同的值传递 pathSide 属性作为键

在此示例中,我们使用“right”作为值传递 pathSide 属性作为键。因此,文本将绘制在路径的右侧。

<!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 pathSide property as key with a different value</h2> <p>You can see that the text is drawn on the right side of the path</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 a path instance var path = new fabric.Path("M 0 0 C 100 -100 150 -100 300 0", { strokeWidth: 1, stroke: "blue", fill: "white", strokeWidth: 4, }); // Initiate an itext object var itext = new fabric.IText("Add sample text here.", { width: 300, left: 110, top: 70, fill: "red", path: path, pathSide: "right", }); // Add it to the canvas canvas.add(itext); </script> </body> </html>

更新于:2022年9月13日

293 次浏览

启动您的职业生涯

完成课程获得认证

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