FabricJS – 如何在水平和垂直方向上等比例縮放影像?
在本教程中,我們將學習如何使用 FabricJS 在水平和垂直方向上等比例縮放影像。我們可以透過建立fabric.Image的例項來建立影像物件。由於它是 FabricJS 的基本元素之一,因此我們也可以透過應用角度、不透明度等屬性來輕鬆自定義它。為了在水平和垂直方向上等比例縮放影像,我們使用scale方法。
語法
scale(value: Number): fabric.Object
引數
scale − 此引數接受一個數字,該數字設定影像物件的縮放因子。
影像物件的預設外觀
示例
讓我們看一個程式碼示例,看看在不使用scale方法時影像物件是什麼樣子。在這種情況下,我們的影像物件不會在水平和垂直方向上縮放。
<!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>
使用自定義值傳遞scale方法
示例
在本例中,我們將看到現在為scale方法賦值,該方法在水平和垂直方向上等比例縮放我們的影像物件。由於我們已將值傳遞為2,因此該值將是現在考慮的縮放因子。
<!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 scale method with a custom value</h2> <p> You can see that the object has been scaled in horizontal and 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, }); // Using the scale method image.scale(2); // 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