如何在 FabricJS 中為線條新增動畫?
在本教程中,我們將學習如何在 FabricJS 中為線條新增動畫。線條元素是 FabricJS 提供的基本元素之一,用於建立直線。因為線條元素在幾何上是一維的,並且不包含內部,所以它們永遠不會被填充。我們可以透過建立fabric.Line的例項,指定線條的 x 和 y 座標,並將其新增到畫布上來建立線條物件。為了為線條例項新增動畫,我們使用 animate 方法。
語法
animate(property: String | Object, value: Number | Object)
引數
屬性 − 此屬性接受字串或物件值,用於確定我們要為哪些屬性新增動畫。
值 − 此屬性接受數字或物件值,用於確定為屬性新增動畫的值。
線條物件的預設外觀
示例
讓我們來看一個程式碼示例,看看在不使用 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 Line object</h2> <p>You can see that the line has no animation</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 Line object var line = new fabric.Line([200, 100, 100, 40], { stroke: "blue", strokeWidth: 20, }); // Add it to the canvas canvas.add(line); </script> </body> </html>
使用 animate 方法
示例
在此示例中,我們將看到如何透過使用 animate 方法輕鬆建立我們自己的動畫。第一個引數是我們想要為其新增動畫的屬性。例如,這裡我們使用了 angle 和 left 屬性作為引數,以便更改其角度和位置。此屬性還允許我們使用相對值,就像我們指定的值為 +=100 和 90 一樣,這使得線條分別移動和改變角度。
<!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> // Initiate a canvas instance var canvas = new fabric.Canvas("canvas"); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); // Initiate a Line object var line = new fabric.Line([200, 100, 100, 40], { stroke: "blue", strokeWidth: 20, }); // Using the animate method line.animate("left", "+=100", { onChange: canvas.renderAll.bind(canvas), }); line.animate("angle", "90", { onChange: canvas.renderAll.bind(canvas), }); // Add it to the canvas canvas.add(line); </script> </body> </html>
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP