如何使用 FabricJS 在文字中新增動畫?
在本教程中,我們將學習如何使用 FabricJS 在文字中新增動畫。我們可以透過新增 fabric.Text 的例項在畫布上顯示文字。它不僅允許我們移動、縮放和更改文字的尺寸,還提供其他功能,例如文字對齊、文字修飾、行高,這些功能可以透過 textAlign、underline 和 lineHeight 屬性分別獲得。同樣,我們也可以使用 animate 方法對文字進行動畫處理。
語法
animate(property: String | Object, value: Number | Object)
引數
屬性 − 此屬性接受字串或物件值,用於確定我們要為其設定動畫的屬性。
值 − 此屬性接受數字或物件值,用於確定為屬性設定動畫的值
示例 1
文字物件的預設外觀
讓我們看一個程式碼示例,看看當不使用 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> // 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("Sparse is better than dense!", { width: 300, left: 50, top: 70, fill: "green", }); // Add it to the canvas 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> // 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("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) }); // Add it to the canvas canvas.add(text); </script> </body> </html>
廣告