如何使用 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.com/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.com/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>
广告