如何在 FabricJS 中設定 IText 的路徑側?


在本教程中,我們將學習如何在 FabricJS 中設定 IText 的路徑側。IText 類是在 FabricJS 1.4 版本中引入的,它擴充套件了 fabric.Text 並用於建立 IText 例項。IText 例項使我們可以自由地選擇、剪下、貼上或新增新文字,無需額外的配置。它還支援各種按鍵組合和滑鼠/觸控組合,使文字具有互動性,而這些功能在 Text 中是沒有的。

然而,基於 IText 的文字框允許我們調整文字矩形的尺寸並自動換行。這對於 IText 來說是不正確的,因為高度不會根據換行進行調整。我們可以使用各種屬性來操作 IText 物件。同樣,我們可以使用 pathSide 屬性為文字指定路徑側。

語法

new fabric.IText( text: String , { pathSide: String }: Object)

引數

  • text − 此引數接受一個字串,即我們想要顯示為文字的文字字串。

  • options (可選) − 此引數是一個物件,它為我們的 IText 物件提供額外的自定義選項。使用此引數可以更改與 IText 物件相關的許多屬性,例如顏色、游標、筆劃寬度以及 pathSide 屬性。

選項鍵

  • pathSide − 此屬性接受一個字串值,允許我們指定應在路徑的哪一側繪製文字。預設值為“left”。

示例 1

使用預設值傳遞 pathSide 屬性作為鍵

讓我們來看一個程式碼示例,看看當 pathSide 屬性使用其預設值時 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>Passing the pathSide property as key with its default value</h2> <p>You can see that the text is drawn on the left side of the path</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, stroke: "blue", fill: "white", strokeWidth: 4, }); // Initiate an itext object var itext = new fabric.IText("Add sample text here.", { width: 300, left: 110, top: 70, fill: "red", path: path, pathSide: "left", }); // Add it to the canvas canvas.add(itext); </script> </body> </html>

示例 2

使用不同的值傳遞 pathSide 屬性作為鍵

在此示例中,我們使用“right”作為值傳遞 pathSide 屬性作為鍵。因此,文字將繪製在路徑的右側。

<!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 pathSide property as key with a different value</h2> <p>You can see that the text is drawn on the right side of the path</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, stroke: "blue", fill: "white", strokeWidth: 4, }); // Initiate an itext object var itext = new fabric.IText("Add sample text here.", { width: 300, left: 110, top: 70, fill: "red", path: path, pathSide: "right", }); // Add it to the canvas canvas.add(itext); </script> </body> </html>

更新於:2022年9月13日

293 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.