使用 FabricJS 為多邊形物件新增淡入淡出動畫
我們可以透過建立fabric.Polygon的例項來建立一個多邊形物件。多邊形物件可以由任何由一組連線的直線段組成的封閉形狀來表示。
由於它是 FabricJS 的基本元素之一,因此我們也可以透過應用角度、不透明度等屬性來輕鬆自定義它。為了新增淡入淡出動畫,我們可以將opacity屬性與animate方法結合使用。
語法
animate(property: String | Object, value: Number | Object): fabric.Object | fabric.AnimationContext | Array.<fabric.AnimationContext>
引數
property − 此屬性接受字串或物件值,用於確定我們要動畫化的屬性。
value − 此屬性接受數字或物件值,用於確定動畫化屬性的值。
選項鍵
opacity − 此屬性接受一個數字,允許我們控制物件的不透明度。不透明度屬性的預設值為 1。
示例 1:為多邊形新增淡入動畫
讓我們來看一個程式碼示例,瞭解如何使用animate方法和opacity屬性新增淡入動畫。為了建立淡入效果,我們需要將不透明度從 0(透明)設定為 1(不透明)。我們還添加了緩動選項並將其傳遞給easeInCubic的值,這使得動畫開始緩慢但結束快速。
<!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 fade-in animation to the polygon</h2>
<p>You can see the fade-in effect 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: 600, y: 310 },
{ x: 650, y: 450 },
{ x: 600, y: 480 },
{ x: 550, y: 480 },
{ x: 450, y: 460 },
{ x: 300, y: 210 },
],
{
fill: "#778899",
stroke: "blue",
strokeWidth: 5,
top: 50,
left: 100,
scaleX: 0.5,
scaleY: 0.5,
opacity: 0,
}
);
// Adding it to the canvas
canvas.add(polygon);
// Using the animate method
polygon.animate("opacity", "1", {
onChange: canvas.renderAll.bind(canvas),
easing: fabric.util.ease.easeInCubic,
duration: 5000,
});
</script>
</body>
</html>
示例 2:為多邊形新增淡出動畫
在此示例中,我們將瞭解如何使用animate方法和opacity屬性建立淡出動畫。為了建立淡出效果,我們需要將不透明度從 1(不透明)設定為 0(透明)。
由於我們將duration屬性的值設定為 5000,因此此動畫將持續 5 秒。我們還添加了緩動選項並將其傳遞給easeOutCubic的值,這使得動畫開始快速但結束緩慢。
<!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 fade-out animation to the polygon</h2>
<p>You can see the fade-out effect 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: 600, y: 310 },
{ x: 650, y: 450 },
{ x: 600, y: 480 },
{ x: 550, y: 480 },
{ x: 450, y: 460 },
{ x: 300, y: 210 },
],
{
fill: "#778899",
stroke: "blue",
strokeWidth: 5,
top: 50,
left: 100,
scaleX: 0.5,
scaleY: 0.5,
opacity: 1,
}
);
// Adding it to the canvas
canvas.add(polygon);
// Using the animate method
polygon.animate("opacity", "0", {
onChange: canvas.renderAll.bind(canvas),
easing: fabric.util.ease.easeOutCubic,
duration: 5000,
});
</script>
</body>
</html>
結論
在本教程中,我們使用兩個簡單的示例演示瞭如何使用 FabricJS 為多邊形物件新增淡入淡出動畫。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP