如何使用 FabricJS 序列化 Polygon 物件?
我們可以透過建立 `fabric.Polygon` 的例項來建立一個 Polygon 物件。多邊形物件可以由任何由一組連線的直線段組成的封閉形狀來表示。由於它是 FabricJS 的基本元素之一,我們也可以透過應用角度、不透明度等屬性輕鬆對其進行自定義。
序列化是將物件轉換為適合透過網路傳輸的格式的過程,在本例中是物件的表示形式。為了建立 Polygon 物件的物件表示形式,我們使用 `toObject` 方法。此方法返回例項的物件表示形式。
語法
toObject(propertiesToInclude: Array): Object
引數
`propertiesToInclude` − 此引數接受一個數組,其中包含我們可能想要額外包含在輸出中的任何屬性。此引數是可選的。
示例 1:使用 toObject 方法
讓我們看一個程式碼示例,看看使用 `toObject` 方法時的日誌輸出。在這種情況下,將返回 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>Using the toObject method</h2> <p> You can open console from dev tools and see that the logged output contains the Object representation of the polygon instance </p> <canvas id="canvas"></canvas> <script> // Initiate a canvas instance var canvas = new fabric.Canvas("canvas"); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); // Initiating a polygon object var polygon = new fabric.Polygon( [ { x: -20, y: -35 }, { x: 20, y: -35 }, { x: 40, y: 0 }, { x: 20, y: 35 }, { x: -20, y: 35 }, { x: -40, y: 0 }, ], { stroke: "red", left: 100, top: 50, fill: "black", strokeWidth: 2, strokeLineJoin: "bevil", } ); // Adding it to the canvas canvas.add(polygon); // Using the toObject method console.log( "Object representation of the Polygon instance is: ", polygon.toObject() ); </script> </body> </html>
示例 2:使用 toObject 方法新增其他屬性
讓我們看一個程式碼示例,看看我們如何使用 `toObject` 方法包含其他屬性。在本例中,我們添加了一個名為“PropertyName”的自定義屬性。我們可以將特定屬性作為第二個引數傳遞給 `fabric.Polygon` 例項的 `options` 物件中,並將相同的鍵傳遞給 `toObject` 方法。
<!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>Using toObject method to add additional properties</h2> <p> You can open console from dev tools and see that the logged output contains added property called PropertyName </p> <canvas id="canvas"></canvas> <script> // Initiate a canvas instance var canvas = new fabric.Canvas("canvas"); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); // Initiating a polygon object with PropertyName key // and passed in options object var polygon = new fabric.Polygon( [ { x: -20, y: -35 }, { x: 20, y: -35 }, { x: 40, y: 0 }, { x: 20, y: 35 }, { x: -20, y: 35 }, { x: -40, y: 0 }, ], { stroke: "red", left: 100, top: 50, fill: "black", strokeWidth: 2, strokeLineJoin: "bevil", PropertyName: "property", } ); // Adding it to the canvas canvas.add(polygon); // Using the toObject method console.log( "Object representation of the Polygon instance is: ", polygon.toObject(["PropertyName"]) ); </script> </body> </html>
結論
在本教程中,我們使用兩個簡單的示例演示瞭如何使用 FabricJS 序列化 Polygon 物件。
廣告