如何使用 FabricJS 设置文本框的旋转角度?

fabricjshtml5 canvasjavascript

在本教程中,我们将使用 FabricJS 设置文本框的旋转角度。我们可以自定义、拉伸或移动文本框中写入的文本。为了创建文本框,我们必须创建 fabric.Textbox 类的实例并将其添加到画布。FabricJS 中的 angle 属性定义对象的 2D 旋转角度。我们还有 centeredRotation 属性,允许我们使用文本框的中心点作为转换的原点。

语法

new fabric.Textbox(text: String, { angle: Number, centeredRotation: Boolean }: Object)

参数

  • text − 此参数接受 String,这是我们想要在文本框内显示的文本字符串。

  • options (可选) − 此参数是一个 Object,它为我们的文本框提供额外的自定义。使用此参数,可以更改与文本框相关的属性,例如颜色、光标、笔触宽度和许多其他属性,其中 angle 是其属性。

选项键

  • angle - 此属性接受一个 Number,该数字指定文本框的旋转角度(以度为单位)。

  • centeredRotation - 该属性接受一个 Boolean 值,该值确定文本框的中心是否为变换的原点。

示例 1

angle 作为键传递,并使用自定义值禁用文本框的中心旋转

让我们看一个代码示例,以设置文本框的旋转角度FabricJS。负角度指定逆时针方向,而正角度指定顺时针方向。由于我们已将 centeredRotation 指定为 False 值,因此文本框将以其角点作为旋转中心进行旋转。

<!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 angle as key with a custom value and disabling the centered rotation for the Textbox</h2> <p>You can select and rotate the textbox to verify that it uses its corner point as the center of rotation</p> <canvas id="canvas"></canvas> <script> // 启动一个canvas实例 var canvas = new fabric.Canvas("canvas"); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); // 初始化一个 textbox 文本框对象 var textbox = new fabric.Textbox("Peace begins with a smile.", { backgroundColor: "#b0e0e6", width: 400, top: 70, left: 110, centeredRotation: false, angle: 15, }); // 将其添加到画布 canvas.add(textbox); </script> </body> </html>

示例 2

为文本框启用居中旋转

从此示例中我们可以看到,通过将 centeredRotation 属性设置为 true,我们的文本框现在使用其中心作为旋转中心。在 1.3.4 版之前,centeredScaling 和 centeredRotation 包含在一个名为 centerTransform 的属性中。

<!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>Enabling centered rotation for the textbox</h2> <p>You can select and rotate the textbox to verify that it now uses its center as center of rotation</p> <canvas id="canvas"></canvas> <script> // 启动一个canvas实例 var canvas = new fabric.Canvas("canvas"); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); // 初始化一个 textbox 文本框对象 var textbox = new fabric.Textbox("Peace begins with a smile.", { backgroundColor: "#b0e0e6", width: 400, top: 70, left: 110, centeredRotation: true, angle: 15, }); // 将其添加到画布 canvas.add(textbox); </script> </body> </html>

相关文章