使用 FabricJS 為多邊形物件新增旋轉動畫
我們可以透過建立fabric.Polygon的例項來建立一個多邊形物件。多邊形物件可以由任何由一組連線的直線段組成的封閉形狀來表徵。由於它是 FabricJS 的基本元素之一,因此我們還可以透過應用角度、不透明度等屬性輕鬆地對其進行自定義。為了新增旋轉動畫,我們可以結合使用angle屬性和animate方法。
語法
animate(property: String | Object, value: Number | Object): fabric.Object | fabric.AnimationContext | Array.<fabric.AnimationContext>
引數
property − 此屬性接受字串或物件值,用於確定我們要動畫化的屬性。
value − 此屬性接受數字或物件值,用於確定要動畫化屬性的值。
選項鍵
angle − 此屬性接受一個數字,用於確定物件的旋轉角度(以度為單位)。
示例 1:為多邊形新增旋轉動畫
讓我們看一個程式碼示例,瞭解如何使用animate方法和angle屬性為多邊形新增旋轉動畫。由於我們將angle屬性的值設定為 60 度,因此多邊形將旋轉該角度。由於持續時間設定為 2000,因此動畫將持續 2 秒。
<!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 rotation animation to the polygon</h2>
<p>You can see the rotation animation has been added to the Polygon</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 polygon object
var polygon = new fabric.Polygon(
[
{ x: 60, y: 0 },
{ x: 60, y: 60 },
{ x: 0, y: 60 },
{ x: 0, y: 0 },
],
{
fill: "#ffe4e1",
stroke: "green",
strokeWidth: 5,
top: 50,
left: 100,
}
);
// Adding it to the canvas
canvas.add(polygon);
// Using the animate method
polygon.animate("angle", "60", {
onChange: canvas.renderAll.bind(canvas),
duration: 2000,
});
</script>
</body>
</html>
示例 2:為多邊形新增完整旋轉動畫
在此示例中,我們將瞭解如何使用animate方法和angle屬性建立完整旋轉動畫。完整旋轉是指物件旋轉 360 度。我們可以將角度傳遞為 360 以建立該動畫。在這裡,我們添加了緩動效果為easeOutBounce,它會建立一個指數遞減的拋物線彈跳效果。
<!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 full rotation animation to the polygon</h2>
<p>You can see that the polygon completes a full rotation</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 polygon object
var polygon = new fabric.Polygon(
[
{ x: 60, y: 0 },
{ x: 60, y: 60 },
{ x: 0, y: 60 },
{ x: 0, y: 0 },
],
{
fill: "#ffe4e1",
stroke: "green",
strokeWidth: 5,
top: 90,
left: 100,
}
);
// Adding it to the canvas
canvas.add(polygon);
// Using the animate method
polygon.animate("angle", "360", {
onChange: canvas.renderAll.bind(canvas),
easing: fabric.util.ease.easeOutBounce,
duration: 5000,
});
</script>
</body>
</html>
結論
在本教程中,我們使用兩個簡單的示例演示瞭如何使用 FabricJS 為多邊形物件新增旋轉動畫。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP