如何使用 FabricJS 为折线添加淡入淡出动画?


我们可以通过创建fabric.Polyline实例来创建一个折线对象。折线对象可以由一组连接的直线段来表征。由于它是 FabricJS 的基本元素之一,我们也可以通过应用角度、不透明度等属性来轻松定制它。

由于 FabricJS 本身不支持模糊效果,我们将使用 CSS 为折线添加淡入淡出动画。

语法

filter: blur(Xpx)

这里,“X”是接受一个数值的属性,该数值决定了要应用的模糊量。

示例 1:为折线添加淡入动画

让我们来看一个代码示例,了解如何使用filter属性添加淡入动画。为了创建淡入效果,我们需要创建一个动画,该动画从模糊值为 0px 开始,到模糊值为 5px 结束,如下面的代码示例所示,我们添加了 5 秒的持续时间。

Open Compiler
<!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>Adding blur-in animation to the polyline</h2> <p>You can see the blur-in effect has been added to the polyline</p> <canvas id="canvas"></canvas> <style> @-webkit-keyframes blur { 0% { filter: blur(0px);} 100% { filter: blur(5px);} } #canvas { animation: blur 5s; } </style> <script> // Initiate a canvas instance var canvas = new fabric.Canvas("canvas"); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); // Initiate a polyline object var polyline = new fabric.Polyline( [ { x: 50, y: 0 }, { x: 25, y: 43.30}, { x: -25, y: 43.301 }, { x: -50, y: 0}, { x: -25, y: -43.301}, { x: 25, y: -43.301 }, { x: 50, y: 0 }, ], { fill: "skyblue", stroke: "orange", strokeWidth: 5, top: 50, left: 300, } ); // Adding it to the canvas canvas.add(polyline); </script> </body> </html>

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

示例 2:为折线添加淡出动画

让我们来看一个代码示例,了解如何使用 filter 属性添加淡出动画。为了创建淡出效果,我们需要创建一个动画,该动画从模糊值为 5px 开始,到模糊值为 0px 结束,如下面的代码示例所示,我们添加了 5 秒的持续时间。

Open Compiler
<!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>Adding blur-out animation to the polyline</h2> <p>You can see the blur-out effect has been added to the polyline</p> <canvas id="canvas"></canvas> <style> @-webkit-keyframes blur { 0% { filter: blur(5px);} 100% { filter: blur(0px);} } #canvas { animation: blur 5s; } </style> <script> // Initiate a canvas instance var canvas = new fabric.Canvas("canvas"); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); // Initiate a polyline object var polyline = new fabric.Polyline( [ { x: 50, y: 0 }, { x: 25, y: 43.30}, { x: -25, y: 43.301 }, { x: -50, y: 0}, { x: -25, y: -43.301}, { x: 25, y: -43.301 }, { x: 50, y: 0 }, ], { fill: "skyblue", stroke: "orange", strokeWidth: 5, top: 50, left: 300, } ); // Adding it to the canvas canvas.add(polyline); </script> </body> </html>

更新于:2023年2月16日

253 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告