如何使用 FabricJS 返回多邊形物件的無資料表示?
我們可以透過建立 fabric.Polygon 的例項來建立 Polygon 物件。多邊形物件可以由任何由一組連線的直線段組成的閉合形狀來表徵。由於它是 FabricJS 的基本元素之一,因此我們還可以透過應用角度、不透明度等屬性輕鬆地對其進行自定義。我們可以使用 toDatalessObject 方法返回多邊形的無資料物件表示。此方法返回多邊形例項的物件表示。
語法
toDatalessObject( propertiesToInclude: Array ): Object
引數
propertiesToInclude (可選) − 此引數接受一個陣列,允許我們新增任何希望包含在輸出中的屬性。此引數是可選的。
示例 1:使用 toDatalessObject 方法
讓我們來看一個程式碼示例,說明如何使用 toDatalessObject 方法在控制檯中檢視 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 toDatalessObject method</h2> <p> You can open console from dev tools and see that the logged output contains the dataless 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 }, ], { top: 50, left: 50, } ); // Adding it to the canvas canvas.add(polygon); // Using the toDatalessObject method console.log( "Dataless object representation of a Polygon instance is: ", polygon.toDatalessObject() ); </script> </body> </html>
示例 2:使用 toDatalessObject 方法新增其他屬性
讓我們來看一個程式碼示例,說明如何使用 toDatalessObject 方法包含其他屬性。在這種情況下,我們添加了一個名為“name”的自定義屬性。我們可以將特定屬性作為選項物件中的第二個引數傳遞給 fabric.Polygon 例項,並將相同的鍵傳遞給 toDatalessObject 方法。
<!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 toDatalessObject method to add additional properties</h2> <p> You can open console from dev tools and see that the logged output contains the property called name </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 name key // 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 }, ], { top: 50, left: 50, name: "Polygon instance", } ); // Adding it to the canvas canvas.add(polygon); // Using the toDatalessObject method console.log( "Dataless object representation of a Polygon instance is: ", polygon.toDatalessObject(["name"]) ); </script> </body> </html>
結論
在本教程中,我們使用兩個簡單的示例演示瞭如何使用 FabricJS 返回 Polygon 的無資料物件表示。
廣告