如何使用 FabricJS 查找线条实例的复杂度?
在本教程中,我们将学习如何使用 FabricJS 查找线条的复杂度。线条元素是 FabricJS 提供的基本元素之一,用于创建直线。由于线条元素在几何上是一维的,并且不包含内部,因此它们永远不会被填充。我们可以通过创建fabric.Line的实例,指定线条的 x 和 y 坐标并将其添加到画布上来创建线条对象。为了获取线条对象的复杂度,我们使用 complexity 方法。如果当前对象直接继承自基类而不是子类,则此方法将返回 1。
语法
complexity(): Number
使用 complexity 方法
示例
让我们来看一个代码示例,看看当我们使用 complexity 方法获取线条实例的复杂度时,记录的输出是什么。除非是子类,否则复杂度为 1。
<!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 complexity method</h2> <p>You can open console from dev tools and 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 Line object var line = new fabric.Line([70, 100, 150, 200], { stroke: "blue", }); // Add it to the canvas canvas.add(line); // Using the complexity method console.log("The complexity of Line instance is: ", line.complexity()); </script> </body> </html>
使用 complexity 方法比较不同的对象
示例
在这个例子中,我们使用了 complexity 方法来比较线条实例和多边形实例的复杂度。您可以从开发者工具打开控制台,查看它们的复杂度不同。
<!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 complexity method to compare different objects</h2> <p>You can open console from dev tools and see that the complexities are different </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 Line object var line = new fabric.Line([70, 100, 150, 200], { stroke: "blue", }); // Initiate a Polygon object var polygon = new fabric.Polyline( [ { x: 50, y: 30 }, { x: 105, y: 10 }, { x: 160, y: 30 }, { x: 100, y: 150 }, ], { fill: "red", left: 300, top: 70, } ); // Add both to the canvas canvas.add(line); canvas.add(polygon); // Using the complexity method console.log("The complexity of Line instance is: ", line.complexity()); console.log( "The complexity of Polygon instance is: ", polygon.complexity() ); </script> </body> </html>
广告