如何在 FabricJS 中使用 IText 更改文字對齊方式到路徑?
在本教程中,我們將學習如何在 FabricJS 中使用 IText 更改文字對齊方式到路徑。IText 類是在 FabricJS 1.4 版本中引入的,擴充套件了 fabric.Text,用於建立 IText 例項。IText 例項使我們能夠自由選擇、剪下、貼上或新增新文字,而無需額外的配置。此外,還支援各種按鍵組合和滑鼠/觸控組合,使文字具有互動性,而這些功能在 Text 中是不提供的。
但是,基於 IText 的文字框允許我們調整文字矩形的大小並自動換行。這對於 IText 來說是不正確的,因為高度不會根據換行進行調整。我們可以使用各種屬性來操作 IText 物件。同樣,我們可以使用 pathAlign 屬性指定文字對齊到路徑的方式。
語法
new fabric.IText( text: String , { pathAlign: String }: Object)
引數
text − 此引數接受一個字串,即我們希望顯示為文字的文字字串。
options (可選) − 此引數是一個物件,它為我們的 IText 物件提供額外的自定義。使用此引數,可以更改與 IText 物件相關的顏色、游標、筆劃寬度和許多其他屬性,其中 pathAlign 是一個屬性。
選項鍵
pathAlign − 此屬性接受一個字串值,該值確定每個字元相對於路徑的垂直位置。可能的值為“baseline”、“ascender”、“descender”和“center”。預設值為 baseline。下面解釋了可能的值
baseline − 將文字的基線放在路徑上。
ascender − 將文字放在路徑內部。
descender − 將文字放在路徑外部。
center − 將文字行放置在路徑的中心。
示例 1
pathAlign 屬性的預設值
讓我們看一個程式碼示例,瞭解當我們沒有使用pathAlign屬性時文字路徑是什麼樣子。這裡,“M”命令表示移動,並指示無形的筆移動到點 0,0。“C”命令表示“三次貝塞爾曲線”,它使筆繪製一條貝塞爾曲線。由於我們沒有使用 pathAlign 屬性,因此將遵循預設的路徑對齊方式,即 baseline。
<!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 value of path alignment</h2> <p>You can see the default path alignment</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 path instance var path = new fabric.Path("M 0 0 C 100 -100 150 -100 300 0", { strokeWidth: 1, }); // Initiate an itext object var itext = new fabric.IText("Add sample text here.", { width: 300, left: 60, top: 70, fill: "red", path: path, pathSide: "left", pathStartOffset: 0, }); // Add it to the canvas canvas.add(itext); </script> </body> </html>
示例 2
將 pathAlign 屬性作為鍵傳遞
在此示例中,我們已將 pathAlign 屬性作為鍵傳遞。由於我們已將值傳遞為“ascender”,因此每個字元的對齊方式現在將更改。
<!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 pathAlign property as key </h2> <p>You can see that the path alignment has been changed</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 path instance var path = new fabric.Path("M 0 0 C 100 -100 150 -100 300 0", { strokeWidth: 1, }); // Initiate an itext object var itext = new fabric.IText("Add sample text here.", { width: 300, left: 60, top: 70, fill: "red", path: path, pathSide: "left", pathStartOffset: 0, pathAlign: "ascender" }); // Add it to the canvas canvas.add(itext); </script> </body> </html>
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP