如何使用 FabricJS 獲取影像物件的縮放比例?
在本教程中,我們將學習如何使用 FabricJS 獲取影像物件的縮放比例。我們可以透過建立 fabric.Image 的例項來建立一個影像物件。由於它是 FabricJS 的基本元素之一,因此我們也可以透過應用角度、不透明度等屬性輕鬆自定義它。為了獲取影像物件的縮放比例,我們使用 getObjectScaling 方法。
語法
getObjectScaling(): Object
使用 getObjectscaling 方法
示例
讓我們來看一個程式碼示例,看看使用 getObjectScaling 方法時控制檯的輸出。在這種情況下,控制檯將顯示預設的 scaleX 和 scaleY 值,它們都是 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 getObjectscaling 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 getObjectScaling method console.log("The scale factor is", image.getObjectScaling()); </script> </body> </html>
使用 getObjectScaling 方法並傳遞 scaleX 屬性
示例
讓我們來看一個程式碼示例,看看將 getObjectScaling 方法與 scaleX 屬性結合使用時控制檯的輸出。在這種情況下,影像物件的 scaleX 值將顯示為 2,而 scaleY 值將保持不變。
<!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 getObjectScaling method and passing the scaleX property</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, scaleX: 2, }); // Add it to the canvas canvas.add(image); // Using getObjectScaling method console.log("The scale factor is", image.getObjectScaling()); </script> </body> </html>
廣告