如何使用 FabricJS 識別 Image 例項的型別?
在本教程中,我們將學習如何識別 FabricJS 中 Image 例項的型別。我們可以透過建立fabric.Image 的例項來建立一個 Image 物件。由於它是 FabricJS 的基本元素之一,我們也可以透過應用角度、不透明度等屬性輕鬆自定義它。為了識別 Image 例項的型別,我們使用isType 方法。
語法
isType(type: String): Boolean
引數
type − 此引數接受一個字串,指定我們要檢查的型別。
使用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://tutorialspoint.tw/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 isType method 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://tutorialspoint.tw/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 isType method console.log( "Is the specified type identical to an image instance? : ", image.isType("circle") ); </script> </body> </html>
廣告