如何在 FabricJS 中设置文本动画的持续时间?


在本教程中,我们将学习如何使用 FabricJS 设置动画文本的持续时间。我们可以通过添加 fabric.Text 实例来在画布上显示文本。它不仅允许我们移动、缩放和更改文本的尺寸,还提供额外的功能,例如文本对齐、文本修饰、行高,这些功能可以通过 textAlign、underline 和 lineHeight 属性分别获得。同样,我们也可以使用 duration 属性更改动画文本的持续时间。

语法

animate(property: String | Object, value: Number | Object, { duration: Number })

参数

  • 属性 (property) − 此属性接受字符串 (String)对象 (Object) 值,用于确定我们要动画化的属性。

  • 值 (value) − 此属性接受数字 (Number)对象 (Object) 值,用于确定要动画化属性的值。

选项键

  • 持续时间 (duration) − 此属性接受数字 (Number)。它可以用来更改动画的持续时间。默认值为 500 毫秒。

示例 1

使用 duration 属性的默认值

让我们来看一个代码示例,看看当 animate 方法与 duration 属性的默认值一起使用时,我们的文本对象是什么样的。在这种情况下,动画的持续时间将为 500 毫秒。

<!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 default value of duration property</h2> <p>You can see that the skewY animation occurs for 500ms</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 text object var text = new fabric.Text("ADD SAMPLE
text here."
, { width: 300, left: 60, top: 70, fill: "#ccccff", stroke: "black", strokeWidth: 2, fontSize: 50, }); // Using the animate method text.animate("skewY", "-=10", { onChange: canvas.renderAll.bind(canvas), duration: 500, }); // Add it to the canvas canvas.add(text); </script> </body> </html>

示例 2

使用 animate 方法并传递 duration 选项

在这个例子中,我们将看到如何通过使用 animate 属性以及 duration 选项来控制动画的持续时间。在本例中,我们将持续时间设置为 2000 毫秒,这就是为什么 skewY 动画持续 2000 毫秒。

<!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 animate method and passing the duration option</h2> <p>You can see that the skewY animation occurs for 2000ms</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 text object var text = new fabric.Text("ADD SAMPLE
text here."
, { width: 300, left: 60, top: 70, fill: "#ccccff", stroke: "black", strokeWidth: 2, fontSize: 50 }); // Using the animate method text.animate('skewY', '-=10', { onChange: canvas.renderAll.bind(canvas), duration: 2000 }); // Add it to the canvas canvas.add(text); </script> </body> </html>

更新于: 2022年9月14日

220 次浏览

启动你的职业生涯

完成课程获得认证

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