FabricJS – 如何将图像对象缩放至指定高度?


在本教程中,我们将学习如何使用 FabricJS 将图像对象缩放至指定高度。我们可以通过创建 `fabric.Image` 实例来创建一个图像对象。由于它是 FabricJS 的基本元素之一,我们也可以通过应用角度、不透明度等属性轻松自定义它。为了将图像对象缩放至指定高度,我们使用 `scaleToHeight` 方法。

语法

scaleToHeight(value: Number, absolute: Boolean): fabric.Object 

参数

  • value − 此参数接受一个数字,该数字确定图像对象的新高度值。

  • absolute − 此参数接受一个布尔值,该值决定是否忽略视口。

图像对象的默认外观

示例

让我们看一个代码示例,看看在不使用 `scaleToHeight` 方法时图像对象的外观。在这种情况下,图像对象不会在水平或垂直方向上缩放。

<!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>Default appearance of the Image object</h2> <p> You can see that the object has not been scaled in horizontal or vertical direction </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, }); // Add it to the canvas canvas.add(image); </script> </body> </html>

使用自定义值传递 `scaleToHeight` 方法

示例

在这个示例中,我们将看到将值赋给 `scaleToHeight` 方法如何将图像对象缩放至指定高度。由于我们传入的值为 100,因此这将是图像对象的新高度。

<!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>Passing the scaleToHeight method with a custom value</h2> <p>You can see that the new height of our image object is 100</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, }); // Using scaleToHeight method image.scaleToHeight(100, false); // Add it to the canvas canvas.add(image); </script> </body> </html>

更新于:2022年10月27日

761 次浏览

开启您的职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.