如何使用 FabricJS 返回多边形对象的无数据表示?
我们可以通过创建 fabric.Polygon 的实例来创建 Polygon 对象。多边形对象可以由任何由一组连接的直线段组成的闭合形状来表征。由于它是 FabricJS 的基本元素之一,因此我们还可以通过应用角度、不透明度等属性轻松地对其进行自定义。我们可以使用 toDatalessObject 方法返回多边形的无数据对象表示。此方法返回多边形实例的对象表示。
语法
toDatalessObject( propertiesToInclude: Array ): Object
参数
propertiesToInclude (可选) − 此参数接受一个数组,允许我们添加任何希望包含在输出中的属性。此参数是可选的。
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
示例 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 的无数据对象表示。
广告