如何使用 FabricJS 设置 IText 变换的垂直原点?
在本教程中,我们将学习如何使用 FabricJS 设置 IText 变换的垂直原点。IText 类是在 FabricJS 1.4 版本中引入的,它扩展了 fabric.Text 并用于创建 IText 实例。IText 实例使我们可以自由地选择、剪切、粘贴或添加新文本,无需额外的配置。还支持各种按键组合和鼠标/触摸组合,使文本具有交互性,而 Text 中没有提供这些功能。
然而,基于 IText 的文本框允许我们调整文本矩形的尺寸并自动换行。这对于 IText 来说并不适用,因为高度不会根据换行进行调整。我们可以使用各种属性来操作 IText 对象。同样,我们也可以使用 originY 属性设置变换的垂直原点。
语法
new fabric.IText(text: String , { originY : String }: Object)
参数
text − 此参数接受一个字符串,即我们要显示的文本字符串。
options (可选) − 此参数是一个对象,它为我们的 IText 对象提供了额外的自定义选项。使用此参数,可以更改与该对象的许多属性相关的颜色、光标、边框宽度等,其中 originY 是一个属性。
选项键
originY − 此属性接受一个字符串值,允许我们设置变换的垂直原点。可能的值为“top”、“bottom”和“center”。其默认值为“top”。
示例 1
IText 对象的默认外观
让我们来看一个代码示例,看看当不使用 originY 属性时,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 the vertical origin of transformation is towards top</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: "#e75c22", } ); // Add it to the canvas canvas.add(itext); </script> </body> </html>
示例 2
将 originY 属性作为键传递值
在这个示例中,我们将看到为 originY 属性赋值如何改变变换的垂直原点。我们在本示例中使用了两个 IText 对象来显示差异。在我们的第一个 IText 对象中,由于我们传递的值为“bottom”,因此变换的垂直原点现在位于底部。相同的顶部属性 70 应用于两个 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 originY property as key with a value</h2> <p>You can see that the origin of transformation for the first IText object(itext1) is bottom while IText2 maintains the default vertical origin of transformation </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: 310, top: 70, fill: "#e75c22", originY: "bottom", }); // Initiate another itext object var itext2 = new fabric.IText("Second IText object", { width: 300, left: 310, top: 70, fill: "#22e75c", }); // Add both to the canvas canvas.add(itext1); canvas.add(itext2); </script> </body> </html>
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP