在本教程中,我們將學習如何使用 FabricJS 獲取 IText 中單詞的左邊界。 IText 類是在 FabricJS 版本 1.4 中引入的,它擴展了 Fabric.Text 并用于創建 IText 實例。 IText 實例使我們可以自由選擇、剪切、粘貼或添加新文本,而無需額外配置。還有各種支持的按鍵組合和鼠標/觸摸組合使文本具有交互性,而 Text 中未提供這些組合。
然而,基于 IText 的 Textbox 允許我們調整文本矩形的大小并自動換行。對于 IText 來說情況并非如此,因為高度不會根據換行進行調整。我們可以通過使用各種屬性來操作 IText 對象。同樣,我們也可以使用findWordBoundaryLeft方法找到單詞的左邊界
語法
findWordBoundaryLeft(startFrom: Number): Number
登錄后復制
參數
startFrom – 此參數接受一個Number,它表示當前選擇索引,將為其返回該單詞左邊界的新選擇索引值。
示例 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>
登錄后復制
以上就是如何使用 FabricJS 獲取 IText 中單詞的左邊界?的詳細內容,更多請關注www.92cms.cn其它相關文章!






