如何使用 FabricJS 识别图像实例的类型?
fabricjsjavascripthtml5 canvas
在本教程中,我们将学习如何在 FabricJS 中识别图像实例的类型。我们可以通过创建 fabric.Image 实例来创建图像对象。由于它是 FabricJS 的基本元素之一,我们还可以通过应用角度、不透明度等属性轻松地对其进行自定义。为了识别图像实例的类型,我们使用 isType 方法。
语法
isType(type: String): Boolean
参数
type − 此参数接受一个 String,它指定我们要检查的类型。
使用 isType 方法
示例
让我们看一个代码示例,以查看使用 isType 方法时记录的输出。 isType 方法根据实例的类型是否与我们要检查的类型匹配来返回 true 或 false 值。在本例中,由于类型匹配,因此返回 true 值。
<!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 isType method</h2> <p> You can open console from dev tools and see that the logged output contains a true value </p> <canvas id="canvas"></canvas> <img src="https://www.tutorialspoint.com/images/logo.png" id="img1" style="display: none" /> <script> // 启动一个canvas实例 var canvas = new fabric.Canvas("canvas"); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); // 初始化 image 图像元素 var imageElement = document.getElementById("img1"); // 初始化一个图像对象 var image = new fabric.Image(imageElement, { top: 50, left: 110, }); // 将其添加到画布 canvas.add(image); // 使用 isType 方法 console.log( "Is the specified type identical to an image instance? : ", image.isType("image") ); </script> </body> </html>
使用 isType 方法并传入不同的值
示例
在此示例中,我们使用 isType 检查指定的圆圈类型是否与图像实例相同。此处返回 false 值,因为它们不相同。
<!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 isType method with a different value</h2> <p> You can open console from dev tools and see that the logged output contains a false value </p> <canvas id="canvas"></canvas> <img src="https://www.tutorialspoint.com/images/logo.png" id="img1" style="display: none" /> <script> // 启动一个canvas实例 var canvas = new fabric.Canvas("canvas"); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); // 初始化 image 图像元素 var imageElement = document.getElementById("img1"); // 初始化一个图像对象 var image = new fabric.Image(imageElement, { top: 50, left: 110, }); // 将其添加到画布 canvas.add(image); // 使用 isType 方法 console.log( "Is the specified type identical to an image instance? : ", image.isType("circle") ); </script> </body> </html>