如何使用 FabricJS 使多邊形物件對旋轉事件做出反應?
我們可以透過建立fabric.Polygon的例項來建立一個多邊形物件。多邊形物件可以由任何由一組連線的直線段組成的閉合形狀來表徵。由於它是 FabricJS 的基本元素之一,因此我們還可以透過應用角度、不透明度等屬性輕鬆地自定義它。我們使用rotating事件來演示如何使多邊形物件對透過控制元件進行旋轉做出反應。
語法
polygon.on(“rotating”, callbackFunction);
示例 1:顯示物件如何對旋轉事件做出反應
讓我們來看一個程式碼示例,說明如何使多邊形物件對rotating事件做出反應。在這種情況下,一旦我們點選多邊形物件並透過中間旋轉控制元件旋轉它,我們就會看到記錄的輸出。這是因為在物件旋轉時,旋轉事件會連續觸發。
<!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>Displaying how the object reacts to the rotating event</h2>
<p>You can rotate the object to see the callback function fired</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 instance
var polygon = new fabric.Polygon(
[
{ x: 500, y: 20 },
{ x: 550, y: 60 },
{ x: 550, y: 200 },
{ x: 350, y: 200 },
{ x: 350, y: 60 },
{ x: 500, y: 20 },
],
{
fill: "red",
stroke: "blue",
strokeWidth: 2,
objectCaching: false,
}
);
// Adding it to the canvas
canvas.add(polygon);
// Using the rotating event
polygon.on("rotating", () => {
canvas.renderAll();
console.log("The polygon object is rotating");
});
</script>
</body>
</html>
示例 2:旋轉發生時更改填充顏色
讓我們來看一個程式碼示例,瞭解如何在rotating事件發生時更改填充顏色。我們可以使用物件的中間旋轉 (mtr) 控制元件來旋轉畫布上的物件。在這裡,當我們使用其 mtr 控制元件旋轉多邊形物件時,填充顏色將更改為“綠色”。
<!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>Changing the fill colour when rotate happens</h2>
<p>
You can see that the fill colour changes when the polygon is rotated
</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 instance
var polygon = new fabric.Polygon(
[
{ x: 500, y: 20 },
{ x: 550, y: 60 },
{ x: 550, y: 200 },
{ x: 350, y: 200 },
{ x: 350, y: 60 },
{ x: 500, y: 20 },
],
{
fill: "red",
stroke: "blue",
strokeWidth: 2,
objectCaching: false,
top: 50,
left: 30,
scaleX: 0.5,
scaleY: 0.5
}
);
// Adding it to the canvas
canvas.add(polygon);
// Using the rotating event
polygon.on("rotating", () => {
polygon.set("fill", "green")
canvas.renderAll();
});
</script>
</body>
</html>
結論
在本教程中,我們使用了兩個簡單的示例來演示如何使用 FabricJS 使多邊形物件對旋轉事件做出反應。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP