如何使用 FabricJS 在文本中添加动画?

fabricjsjavascripthtml5 canvas更新于 2025/4/24 5:32:17

在本教程中,我们将学习如何使用 FabricJS 在文本中添加动画。我们可以通过添加 fabric.Text 实例在画布上显示文本。它不仅允许我们移动、缩放和更改文本的尺寸,而且还提供其他功能,如文本对齐、文本装饰、行高,这些功能可分别通过属性 textAlign、underline 和 lineHeight 获取。类似地,我们也可以使用 animate 方法为文本设置动画。

语法

animate(property: String | Object, value: Number | Object)

参数

  • property - 此属性接受 String 或 Object 值,该值确定我们要为哪些属性设置动画。

  • value - 此属性接受 Number 或 Object 值,该值确定要为属性设置动画的值

示例 1

Text 对象的默认外观

让我们看一个代码示例,看看当 animate 方法未启用时我们的文本对象是什么样子使用。在这种情况下,不会显示任何动画。

<!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 Text object</h2> <p>You can see that the text has no animation</p> <canvas id="canvas"></canvas> <script> // 启动一个canvas实例 var canvas = new fabric.Canvas("canvas"); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); // Initiate a text object var text = new fabric.Text("Sparse is better than dense!", { width: 300, left: 50, top: 70, fill: "green", }); // 将其添加到画布 canvas.add(text); </script> </body> </html>

示例 2

使用 animate 方法

在此示例中,我们将了解如何使用 animate 属性轻松创建自己的动画。第一个参数是我们要设置动画的属性。例如,在这里,我们使用 stroke 属性作为参数来更改其颜色。此属性还允许我们使用相对值,就像我们将 left 值指定为 +=100 一样,这会使文本移动。

<!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</h2> <p>You can see the animation now</p> <canvas id="canvas"></canvas> <script> // 启动一个canvas实例 var canvas = new fabric.Canvas("canvas"); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); // Initiate a text object var text = new fabric.Text("Sparse is better than dense!", { width: 700, left: 50, top: 70, fill: "#ccccff", stroke: "black", strokeWidth: 2, fontSize: 25 }); // Using the animate method text.animate('stroke', '87ceeb', { onChange: canvas.renderAll.bind(canvas) }) text.animate('left', '+=100', { onChange: canvas.renderAll.bind(canvas) }); // 将其添加到画布 canvas.add(text); </script> </body> </html>

相关文章


有用资源