如何使用 FabricJS 獲取 IText 中單詞的左邊界?


在本教程中,我們將學習如何使用 FabricJS 獲取 IText 中單詞的左邊界。IText 類是在 FabricJS 1.4 版本中引入的,它擴充套件了 fabric.Text,用於建立 IText 例項。IText 例項使我們能夠自由地選擇、剪下、貼上或新增新文字,而無需額外的配置。它還支援各種鍵盤組合和滑鼠/觸控組合,使文字具有互動性,而這些功能在 Text 中是不提供的。

然而,基於 IText 的文字框允許我們調整文字矩形的大小並自動換行。這對於 IText 來說是不正確的,因為高度不會根據換行進行調整。我們可以使用各種屬性來操作 IText 物件。同樣,我們也可以使用 findWordBoundaryLeft 方法找到單詞的左邊界。

語法

findWordBoundaryLeft(startFrom: Number): Number

引數

  • startFrom − 此引數接受一個數字,表示當前選擇索引,將返回該單詞左邊界的新的選擇索引值。

示例 1

使用 findWordBoundaryLeft 方法

讓我們看一個程式碼示例,看看使用 findWordBoundaryLeft 方法時記錄的輸出。在這裡,我們傳遞的值為 5,這意味著我們想要檢查第二個單詞的左邊界。因此,返回值將為 4。

<!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 findWordBoundaryLeft method</h2> <p> You can open console from dev tools and see that the left boundary 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: 110, top: 70, fill: "red", }); // Add it to the canvas canvas.add(itext); // Using findWordBoundaryLeft method console.log("The new selection index is: ", itext.findWordBoundaryLeft(5)); </script> </body> </html>

示例 2

使用 findWordBoundaryLeft 方法計算最後一個單詞的單詞邊界

讓我們看一個程式碼示例,看看如何使用findWordBoundaryLeft 方法找到最後一個單詞的新選擇索引。在這種情況下,我們將 startFrom 引數傳遞了一個值為 17 的值,表示最後一個單詞。因此,返回的新選擇索引值為 16,即最後一個單詞的左邊界。

<!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 findWordBoundaryLeft method to calculate the word boundary for the last word</h2> <p> You can open console from dev tools and see that the left boundary 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: 110, top: 70, fill: "red", }); // Add it to the canvas canvas.add(itext); // Using findWordBoundaryLeft method console.log("The new selection index is: ", itext.findWordBoundaryLeft(17)); </script> </body> </html>

更新於: 2022年9月13日

183 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.