我們可以通過創(chuàng)建fabric.Polygon的實例來創(chuàng)建一個Polygon對象。多邊形對象的特征可以是由一組連接的直線段組成的任何閉合形狀。由于它是 FabricJS 的基本元素之一,我們還可以通過應用角度、不透明度等屬性輕松自定義它。我們使用 selected 和 deselected 事件來演示如何使多邊形對象對用戶選擇和取消選擇對象做出反應。
語法
polygon.on("selected", callbackFunction);
polygon.on("deselected", callbackFunction);
登錄后復制
示例 1:顯示對象如何對所選事件做出反應
讓我們看一個代碼示例,了解如何使多邊形對象對 selected 事件做出反應。單擊該對象將觸發(fā)執(zhí)行回調函數(shù)的 selected 事件。在本例中,只要我們單擊多邊形對象,其填充顏色就會發(fā)生變化并顯示記錄的輸出。
<!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 selected event</h2>
<p>Select the object to see the event 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: "black",
stroke: "blue",
strokeWidth: 2,
objectCaching: false,
}
);
// Adding it to the canvas
canvas.add(polygon);
// Using the selected event
polygon.on("selected", () => {
polygon.fill = "blue";
canvas.renderAll();
console.log("The polygon object is selected");
});
</script>
</body>
</html>
登錄后復制
示例 2:顯示對象如何對取消選擇的事件做出反應
讓我們看一個代碼示例來了解如何使 Polygon 對象對取消選擇事件做出反應。在這里,一旦取消選擇多邊形對象,就會觸發(fā)該事件,從而也改變填充顏色。
<!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 deselected event</h2>
<p>Deselect the object to see the event 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 deselected event
polygon.on("deselected", () => {
polygon.fill = "black";
canvas.renderAll();
console.log("The polygon object is deselected");
});
</script>
</body>
</html>
登錄后復制
結論
在本教程中,我們使用兩個簡單的示例來演示如何使用 FabricJS 讓多邊形對象對選定和取消選定事件做出反應。
以上就是如何使用 FabricJS 使多邊形對象對選定和取消選定事件做出反應?的詳細內容,更多請關注www.92cms.cn其它相關文章!






