在本教程中,我们将学习如何使用 FabricJS 查找线的复杂性。Line 元素是 FabricJS 中提供的基本元素之一。它用于创建直线。因为线元素在几何上是一维的并且不包含内部,所以它们永远不会被填充。我们可以通过创建fabric.Line的实例来创建线条对象,指定线条的 x 和 y 坐标并将其添加到画布。为了获得 Line 对象的复杂度,我们使用复杂度方法。如果当前对象直接继承自基类而不是子类,则此方法将返回 1。
complexity(): Number
当我们使用复杂性方法获取 Line 实例的复杂性时,让我们看一个代码示例来查看记录的输出。除非进行子分类,否则复杂度为 1。
<!DOCTYPE html> <html> <head> <!-- Adding the Fabric JS Library--> <script xx_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> //启动画布实例 var canvas = new fabric.Canvas("canvas"); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); //启动一个 Line 对象 var line = new fabric.Line([70, 100, 150, 200], { stroke: "blue", }); //将其添加到画布 canvas.add(line); //使用复杂性方法 console.log("The complexity of Line instance is: ", line.complexity()); </script> </body> </html>
在这个例子中,我们使用了复杂性方法来比较线实例和多边形实例的复杂性。您可以从开发工具中打开控制台,以查看复杂程度的不同。
<!DOCTYPE html> <html> <head> <!-- Adding the Fabric JS Library--> <script xx_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> //启动画布实例 var canvas = new fabric.Canvas("canvas"); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); //启动一个 Line 对象 var line = new fabric.Line([70, 100, 150, 200], { stroke: "blue", }); //启动一个多边形对象 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, } ); //将两者都添加到画布 canvas.add(line); canvas.add(polygon); //使用复杂性方法 console.log("The complexity of Line instance is: ", line.complexity()); console.log( "The complexity of Polygon instance is: ", polygon.complexity() ); </script> </body> </html>