如何使用 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>
廣告