如何使用 FabricJS 矫正 IText 对象?


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

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

语法

straighten(): fabric.Object

示例 1

在不使用 straighten 方法的情况下传递 angle 属性值

让我们看一个代码示例,了解当不使用 straighten 方法时 IText 对象的外观。straighten 方法通过将对象从当前角度旋转到 0、90、180 或 270 等来矫正对象,具体取决于哪个角度更接近。angle 属性以度为单位设置对象的旋转角度。在这里,我们将其指定为 45。但是,由于我们没有应用 straighten 属性,因此旋转角度将保持 45 度。

<!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 angle property a value without using the straighten method</h2> <p>You can see that the itext object has an angle of 45 degrees</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 "
, { width: 300, left: 210, top: 70, fontSize: 30, fill: "#b666d2", backgroundColor: "#f8f4ff", angle: 45, }); // Add it to the canvas canvas.add(itext); </script> </body> </html>

示例 2

使用 straighten 方法

让我们看一个代码示例,了解当与 angle 属性一起使用 straighten 方法时 IText 对象的外观。虽然我们将旋转角度设置为 45 度,但我们的 itext 对象将通过将其旋转回 0 度来矫正,因为我们使用了 straighten 方法。

<!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>Using the straighten method</h2> <p>You can see that the angle of rotation is 0 degree for the itext object</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 "
, { width: 300, left: 210, top: 70, fontSize: 30, fill: "#b666d2", backgroundColor: "#f8f4ff", angle: 45, }); // Add it to the canvas canvas.add(itext); // Using the straighten method itext.straighten(); </script> </body> </html>

更新于: 2022-09-13

149 次浏览

开启你的 职业生涯

通过完成课程获得认证

立即开始
广告

© . All rights reserved.