如何使用 FabricJS 獲取影像物件的透明度?


在本教程中,我們將瞭解如何使用 FabricJS 獲取影像的不透明度。我們可以透過建立一個 fabric.Image 例項來建立一個影像物件。由於它是 FabricJS 的基本元素之一,我們還可以透過應用角度、不透明度等屬性來輕鬆自定義它。為了獲得影像的不透明度,我們使用 getObjectOpacity 方法。

語法

getObjectOpacity(): Number 

使用 getObjectOpacity 方法

舉例

讓我們看一個程式碼示例,以檢視在使用 getObjectOpacity 方法時記錄的輸出。在這種情況下,將在控制檯中顯示預設的不透明度,即 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 getObjectOpacity method</h2> <p> You can open console from dev tools and see that the logged value is being displayed in the console </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 getObjectOpacity method console.log("The opacity is: ", image.getObjectOpacity()); </script> </body> </html>

使用 getObjectOpacity 方法並傳遞不透明度屬性

舉例

讓我們看一個程式碼示例,以檢視在將 getObjectOpacity 方法與不透明度屬性結合使用時記錄的輸出。在這種情況下,影像物件的透明度已被指定為 0.7,因此記錄的輸出將為 0.7。

<!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 getObjectOpacity method and passing the opacity property</h2> <p> You can open console from dev tools and see that the opacity value is being displayed in the console </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, opacity: 0.7, }); // Add it to the canvas canvas.add(image); // Using getObjectOpacity method console.log("The opacity is: ", image.getObjectOpacity()); </script> </body> </html>

更新於: 27-10-2022

188 次瀏覽

開啟您的 職業生涯

完成課程並獲得認證

立即開始
廣告