如何使用 FabricJS 獲取文字物件的縮放比例?
在本教程中,我們將學習如何使用 FabricJS 獲取文字物件的縮放比例。我們可以透過新增 fabric.Text 的例項在畫布上顯示文字。它不僅允許我們移動、縮放和更改文字的尺寸,還提供額外的功能,例如文字對齊、文字修飾、行高,這些功能可以透過 textAlign、underline 和 lineHeight 屬性分別獲得。我們還可以使用 getObjectScaling 方法找到物件縮放比例。
語法
getObjectScaling()
示例 1
使用 getObjectscaling 方法
讓我們看一個程式碼示例,看看使用 getObjectScaling 方法時記錄的輸出。在這種情況下,控制檯將顯示預設的 scaleX 和 scaleY 值,它們都是 1。
<!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 getObjectScaling method</h2> <p>You can open console from dev tools and see that the logged value is being displayed in the console</p> <canvas id="canvas"></canvas> <script> // Initiate a canvas instance var canvas = new fabric.Canvas("canvas"); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); // Initiate a text object var text = new fabric.Text("Add sample
text here", { width: 300, fill: "green", fontWeight: "bold", }); // Add it to the canvas canvas.add(text); // Using getObjectScaling method console.log("The scale factor is", text.getObjectScaling()); </script> </body> </html>
示例 2
使用 getObjectScaling 方法並傳遞 scaleX 屬性
讓我們看一個程式碼示例,看看將 getObjectScaling 方法與 scaleX 屬性結合使用時記錄的輸出。在這種情況下,文字物件的 scaleX 值將顯示為 2,而 scaleY 值將保持不變。
<!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 getObjectScaling method and passing the scaleX property</h2> <p>You can open console from dev tools and see that the logged value is being displayed in the console </p> <canvas id="canvas"></canvas> <script> // Initiate a canvas instance var canvas = new fabric.Canvas("canvas"); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); // Initiate a text object var text = new fabric.Text("Add sample
text here", { width: 300, fill: "green", fontWeight: "bold", scaleX: 2, }); // Add it to the canvas canvas.add(text); // Using getObjectScaling method console.log("The scale factor is", text.getObjectScaling()); </script> </body> </html>
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP