我們可以透過建立fabric.Polygon的實例來建立一個Polygon物件。多邊形物件的特徵可以是由一組連接的直線段組成的任何閉合形狀。由於它是 FabricJS 的基本元素之一,我們也可以透過應用角度、不透明度等屬性輕鬆自訂它。我們使用 object:modified 事件使多邊形物件對調整大小做出反應。
object:modified
讓我們看一個程式碼範例,了解當不使用 object:modified 事件時多邊形物件如何顯示。在這種情況下,多邊形物件將被添加到畫布中。
<!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>Default appearance of the polygon object</h2> <p>You can see that the polygon object has been added to the canvas</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, } ); // Adding it to the canvas canvas.add(polygon); </script> </body> </html>
讓我們看一個程式碼範例,以查看調整多邊形物件大小時記錄的輸出。我們使用了 object:modified 事件,該事件在任何物件轉換或與物件有關的任何變更結束時觸發。在這種情況下,每次我們更改物件的比例時,縮放後的高度和寬度都會被控制台記錄。
<!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 being resized</h2> <p> You can scale object using corner and open console from dev tools to see that the scaled width and height value of the polygon object is being logged </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, } ); // Adding it to the canvas canvas.add(polygon); // Using object:modified event canvas.on("object:modified", (e) => { canvas.getActiveObjects().forEach((o) => { console.log( "Scaled Height of the polygon is: ", o.getScaledHeight(), "Scaled Width of the polygon is:", o.getScaledWidth() ); }); }); </script> </body> </html>
在本教學中,我們使用兩個簡單的範例來示範如何使用 FabricJS 讓多邊形物件對調整大小事件做出反應。
以上是如何使用 FabricJS 使多邊形物件對調整大小事件做出反應?的詳細內容。更多資訊請關注PHP中文網其他相關文章!