如何使用 FabricJS 查找 Image 实例的复杂度?
在本教程中,我们将学习如何使用 FabricJS 查找 Image 实例的复杂度。我们可以通过创建 fabric.Image 的实例来创建一个 Image 对象。由于它是 FabricJS 的基本元素之一,因此我们也可以通过应用角度、不透明度等属性轻松自定义它。为了找到 Image 实例的复杂度,我们使用complexity 方法。如果当前对象直接继承自基类而不是子类,则此方法将返回 1。
语法
complexity(): Number
使用 complexity 方法
示例
让我们看一个代码示例,了解当我们使用 complexity 方法获取 Image 实例的复杂度时记录的输出。除非是子类,否则复杂度为 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> <img src="https://tutorialspoint.com/images/logo.png" id="img1" style="display: none" /> <script> // Initiate a canvas instance var canvas = new fabric.Canvas("canvas"); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); // Initiating the image element var imageElement = document.getElementById("img1"); // Initiate an Image object var image = new fabric.Image(imageElement, { top: 50, left: 110, }); // Add it to the canvas canvas.add(image); // Using the complexity method console.log("The complexity of Image instance is: ", image.complexity()); </script> </body> </html>
使用 complexity 方法比较不同的对象
示例
在此示例中,我们使用了 complexity 方法来比较 Image 实例和多边形实例的复杂度。您可以从开发者工具中打开控制台,查看它们的复杂度不同。
<!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 the logged output</p> <canvas id="canvas"></canvas> <img src="https://tutorialspoint.com/images/logo.png" id="img1" style="display: none" /> <script> // Initiate a canvas instance var canvas = new fabric.Canvas("canvas"); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); // Initiating the image element var imageElement = document.getElementById("img1"); // Initiate an Image object var image = new fabric.Image(imageElement, { top: 50, left: 50, }); // 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: 450, top: 70, } ); // Add them both to the canvas canvas.add(image); canvas.add(polygon); // Using the complexity method console.log("The complexity of Image instance is: ", image.complexity()); console.log( "The complexity of Polygon instance is: ", polygon.complexity() ); </script> </body> </html>
广告