我們可以透過建立fabric.Polygon的實例來建立一個Polygon物件。多邊形物件的特徵可以是由一組連接的直線段組成的任何閉合形狀。由於它是 FabricJS 的基本元素之一,我們也可以透過應用角度、不透明度等屬性輕鬆自訂它。我們使用 selected 和 deselected 事件來示範如何讓多邊形物件對使用者選擇和取消選取物件做出反應。
polygon.on("selected", callbackFunction); polygon.on("deselected", callbackFunction);
讓我們看一個程式碼範例,了解如何讓多邊形物件對 selected 事件做出反應。按一下該物件將觸發執行回呼函數的 selected 事件。在本例中,只要我們點選多邊形對象,其填滿顏色就會改變並顯示記錄的輸出。
<!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>
讓我們看一個程式碼範例來了解如何使 Polygon 物件對取消選擇事件做出反應。在這裡,一旦取消選擇多邊形對象,就會觸發該事件,從而也改變填充顏色。
<!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 使多邊形物件對選定和取消選定事件做出反應?的詳細內容。更多資訊請關注PHP中文網其他相關文章!