如何使用 FabricJS 使多邊形物件對縮放事件做出反應?
我們可以透過建立fabric.Polygon的例項來建立一個多邊形物件。多邊形物件可以由任何由一組連線的直線段組成的封閉形狀來表示。由於它是 FabricJS 的基本元素之一,我們也可以透過應用角度、不透明度等屬性輕鬆自定義它。我們使用scaling事件來演示多邊形物件如何對縮放做出反應。
語法
polygon.on(“scaling”, callbackFunction);
示例 1:顯示物件如何對縮放事件做出反應
讓我們來看一個程式碼示例,演示當scaling事件發生時多邊形物件如何反應。我們可以透過拖動任何角控制元件來縮放物件。在這裡,當物件正在縮放時,縮放事件將持續觸發。
<!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 scaling event</h2>
<p>
You can scale the polygon object and open the console from dev tools to see the logged output
</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: 0, y: 0 },
{ x: 0, y: 50 },
{ x: 50, y: 50 },
{ x: 50, y: 0 },
],
{
left: 100,
top: 30,
fill: "red",
stroke: "blue",
strokeWidth: 3,
objectCaching: false,
}
);
// Adding it to the canvas
canvas.add(polygon);
// Using the scaling event
polygon.on("scaling", () => {
canvas.renderAll();
console.log("The object is being scaled");
});
</script>
</body>
</html>
示例 2:縮放時更改描邊顏色
讓我們來看一個程式碼示例,瞭解如何在scaling事件發生時更改描邊顏色。我們使用了set方法將多邊形的描邊顏色設定為“橙色”。因此,當我們縮放物件時,它的描邊顏色將變為橙色。
<!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 stroke colour when scaling happens</h2>
<p>
You can see that the stroke colour changes when the polygon is scaled
</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: 5,
objectCaching: false,
top: 50,
left: 30,
scaleX: 0.5,
scaleY: 0.5
}
);
// Adding it to the canvas
canvas.add(polygon);
// Using the scaling event
polygon.on("scaling", () => {
polygon.set("stroke", "orange")
canvas.renderAll();
});
</script>
</body>
</html>
結論
在本教程中,我們使用了兩個簡單的示例來演示如何使用 FabricJS 使多邊形物件對縮放事件做出反應。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP