如何使用 FabricJS 使多邊形物件對傾斜事件做出反應?
我們可以透過建立fabric.Polygon的例項來建立一個多邊形物件。多邊形物件可以由任何由一組連線的直線段組成的閉合形狀來表示。由於它是 FabricJS 的基本元素之一,因此我們也可以透過應用角度、不透明度等屬性輕鬆地對其進行自定義。我們使用傾斜事件來演示多邊形物件在透過控制元件進行傾斜時如何對使用者做出反應。
語法
polygon.on("skewing", callbackFunction);
示例 1:顯示物件如何對傾斜事件做出反應
讓我們來看一個程式碼示例,說明多邊形物件在使用傾斜事件時的反應。透過按住Shift 鍵,然後沿水平或垂直方向拖動中間控制元件,可以沿水平和垂直方向傾斜物件。在物件被傾斜時,會連續觸發傾斜事件。
<!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 skewing event</h2> <p> You can keep skewing the object while the console from dev tools is open 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: 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 skewing event polygon.on("skewing", () => { canvas.renderAll(); console.log("The polygon object is being skewed"); }); </script> </body> </html>
示例 2:傾斜發生時更改填充顏色
讓我們來看一個程式碼示例,瞭解如何在傾斜事件發生時更改填充顏色。我們使用了set方法,這是一個setter,它允許我們指定要更改的屬性。在這裡,每當我們傾斜多邊形時,填充顏色都會更改為“綠色”。
<!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 skew happens</h2> <p> You can see that the fill colour changes when the polygon is skewed </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 skewing event polygon.on("skewing", () => { polygon.set("fill", "green") canvas.renderAll(); }); </script> </body> </html>
結論
在本教程中,我們使用兩個簡單的示例來演示如何使用 FabricJS 使多邊形物件對傾斜事件做出反應。
廣告