如何使用 FabricJS 將文字物件縮放至給定寬度?
在本教程中,我們將學習如何使用 FabricJS 將文字物件縮放至給定寬度。我們可以透過新增 fabric.Text 例項來在畫布上顯示文字。它不僅允許我們移動、縮放和更改文字的尺寸,還提供額外的功能,例如文字對齊、文字修飾、行高,這些功能分別可以透過 textAlign、underline 和 lineHeight 屬性獲得。同樣,我們也可以使用 scaleToWidth 方法將文字物件縮放至給定寬度。
語法
scaleToWidth(value: Number, absolute: Boolean)
引數
value − 此引數接受一個數字,用於確定文字物件的新寬度值。
absolute − 此引數接受一個布林值,用於確定是否忽略視口。
示例 1
文字物件的預設外觀
讓我們來看一個程式碼示例,看看在不使用 scaleToWidth 方法時文字物件的外觀。在這種情況下,文字物件不會在水平或垂直方向上縮放。
<!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 Text object</h2> <p>You can see that the object has not been scaled in horizontal or vertical direction</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.", { left: 60, top: 70, fill: "green", }); // Add it to the canvas canvas.add(text); </script> </body> </html>
示例 2
使用自定義值傳遞 scaleToWidth 方法
在這個例子中,我們將看到如何為 scaleToWidth 方法賦值,將我們的文字物件縮放至給定寬度。由於我們傳入的值為 400,因此這將成為文字物件的新寬度。
<!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 scaleToWidth method with a custom value</h2> <p>You can see that the new width of our text object is 400</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.", { left: 60, top: 70, fill: "green", }); // Using the scaleToWidth method text.scaleToWidth(400, false); // Add it to the canvas canvas.add(text); </script> </body> </html>
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP