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.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); </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.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, }); // Using scaleToHeight method image.scaleToHeight(100, false); // Add it to the canvas canvas.add(image); </script> </body> </html>
廣告
資料結構
網路
關係型資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP