如何使用 FabricJS 使多邊形物件對滑鼠事件做出反應?
我們可以透過建立fabric.Polygon的例項來建立一個多邊形物件。多邊形物件可以由任何由一組連線的直線段組成的封閉形狀來表徵。由於它是 FabricJS 的基本元素之一,因此我們也可以透過應用角度、不透明度等屬性來輕鬆自定義它。我們使用mouseup和mousedown事件來演示多邊形物件如何對使用者觸發的滑鼠事件做出反應。
語法
polygon.on(“mouseup”, callbackFunction); polygon.on(“mousedown”, callbackFunction);
示例 1:顯示物件如何對 mouseup 事件做出反應
讓我們來看一個程式碼示例,說明當觸發mouseup事件時多邊形物件如何做出反應。當用戶釋放滑鼠左鍵時,會發生mouseup事件。在這裡,一旦觸發mouseup事件,筆觸寬度就會更改為 33。
<!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 mouseup event</h2>
<p>
You can select the object and release the left mouse button to see that the stroke width has changed
</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: 2,
objectCaching: false,
}
);
// Adding it to the canvas
canvas.add(polygon);
// Using the mouseup event
polygon.on("mouseup", () => {
polygon.set("strokeWidth", 33);
canvas.renderAll();
});
</script>
</body>
</html>
示例 2:顯示物件如何對 mousedown 事件做出反應
讓我們來看一個程式碼示例,說明當觸發mousedown事件時多邊形物件如何做出反應。當用戶按下按鈕時,會發生mousedown事件。在這裡,我們可以看到物件透過將其筆觸寬度從 33 更改為 2 來對 mousedown 事件做出反應。
<!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 mousedown event</h2>
<p>
You can press the left mouse button to trigger the mousedown event to see that the stroke width has changed
</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: 33,
objectCaching: false,
}
);
// Adding it to the canvas
canvas.add(polygon);
// Using the mousedown event
polygon.on("mousedown", () => {
polygon.set("strokeWidth", 2);
canvas.renderAll();
});
</script>
</body>
</html>
結論
在本教程中,我們使用兩個簡單的示例來演示如何使用 FabricJS 使多邊形物件對滑鼠事件做出反應。
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP