如何使用 FabricJS 查詢影像的原始尺寸?


在本教程中,我們將學習如何使用 FabricJS 查詢影像的原始尺寸。我們可以透過建立fabric.Image的例項來建立影像物件。由於它是 FabricJS 的基本元素之一,我們也可以透過應用角度、不透明度等屬性輕鬆自定義它。為了查詢影像的原始尺寸,我們使用getOriginalSize方法。

語法

getOriginalSize(): Object 

使用getOriginalSize方法

示例

在這個例子中,我們使用了getOriginalSize方法來獲取影像的寬度和高度值。這裡返回的寬度和高度值分別是 311 和 82。

<!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 getOriginalSize method</h2> <p> You can open the console from dev tools to see that the logged output contains the height and width of the Image </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, skewX: 15, }); // Add it to the canvas canvas.add(image); // Using the getOriginalSize method console.log( "The original size of the Image object is: ", image.getOriginalSize() ); </script> </body> </html>

結合cropX屬性使用getOriginalSize方法

示例

讓我們來看一個當getOriginalSize方法與cropX屬性一起使用時的日誌輸出程式碼示例。這裡,我們將值 50 傳遞給 cropX。因此,我們的影像物件將在 x 方向上從原始影像尺寸裁剪 50 畫素。但是,當我們使用getOriginalSize方法時,我們返回的寬度和高度值分別是 311 和 82,這證明了getOriginalSize只會返回影像的原始尺寸。

<!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 getOriginalSize method along with cropX property</h2> <p> You can open the console from dev tools to see that the original size of the image will be returned regardless of having applied image cropping in xdirection </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, skewX: 15, cropX: 50, }); // Add it to the canvas canvas.add(image); // Using the getOriginalSize method console.log( "The original size of the Image object is: ", image.getOriginalSize() ); </script> </body> </html>

更新於:2022年10月27日

976 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.