如何在 FabricJS 中使用 IText 查詢文字框高度?
在本教程中,我們將學習如何在 FabricJS 中使用 IText 查詢文字框高度。IText 類是在 FabricJS 1.4 版本中引入的,擴充套件了 fabric.Text,用於建立 IText 例項。IText 例項使我們能夠自由地選擇、剪下、貼上或新增新文字,而無需額外的配置。它還支援各種鍵盤組合和滑鼠/觸控組合,使文字具有互動性,而這些功能在 Text 中是不提供的。
但是,基於 IText 的文字框允許我們調整文字矩形的大小並自動換行。這對於 IText 來說是不正確的,因為高度不會根據行的換行進行調整。我們可以使用各種屬性來操作 IText 物件。同樣,我們可以使用 calcTextHeight 方法計算文字框高度。
語法
calcTextHeight()
示例 1
使用 calcTextHeight 方法
讓我們看一個程式碼示例,瞭解使用 calcTextHeight 方法時 IText 物件的外觀。在這種情況下,將返回文字高度。
<!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 calcTextHeight method</h2> <p> You can open console from dev tools and see that the text height 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 an itext object var itext = new fabric.IText("Add sample text here.", { width: 300, left: 60, top: 70, fill: "red", }); // Add it to the canvas canvas.add(itext); // Using calcTextHeight method console.log("The text height is: ", itext.calcTextHeight()); </script> </body> </html>
示例 2
使用 calcTextHeight 方法計算增加的文字框高度
在此示例中,我們有意透過新增額外的文字行來增加了文字框的高度。因此,calcTextHeight 方法返回增加的文字框高度,在本例中約為 97.632。
<!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 calcTextHeight method to calculate increased text box height <p> You can open console from dev tools and see that the text height value being displayed in the console has increased </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 an itext object var itext = new fabric.IText("Add sample text here.
Lorem ipsum dolor sit amet", { width: 300, left: 60, top: 70, fill: "red", }); // Add it to the canvas canvas.add(itext); // Using calcTextHeight method console.log("The new text height is: ", itext.calcTextHeight()); </script> </body> </html>
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP