如何使用 FabricJS 獲取文本當前選中部分的樣式?


在本教程中,我們將學習如何使用 FabricJS 獲取文本當前選中部分的樣式。我們可以透過新增 fabric.Text 例項來在畫布上顯示文字。它不僅允許我們移動、縮放和更改文字的尺寸,還提供額外的功能,如文字對齊、文字裝飾、行高,這些功能分別可以透過 textAlign、underline 和 lineHeight 屬性獲得。我們還可以使用 getSelectionStyles 方法查詢當前選擇的樣式。

語法

getSelectionStyles(startIndexopt, endIndexopt, completeopt)

引數

  • startIndexopt − 此引數接受一個數字,表示獲取樣式的起始索引。

  • endIndexopt − 此引數接受一個數字,表示獲取樣式的結束索引。

  • completeopt − 此引數接受一個布林值,決定是否獲取完整樣式。

示例 1

使用 getSelectionStyles 方法

讓我們來看一個程式碼示例,看看使用 getSelectionStyles 方法時的日誌輸出。在這種情況下,將顯示從第 0 個索引到第 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 getSelectionStyles method</h2> <p>You can open console from dev tools and see that the 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 a text object var text = new fabric.Text("Add sample
text here"
, { width: 300, fill: "green", fontWeight: "bold", }); // Add it to the canvas canvas.add(text); // Using getSelectionStyles method console.log("The style is", text.getSelectionStyles(0, 5, true)); </script> </body> </html>

示例 2

使用 getSelectionStyles 方法並傳遞不同的值

讓我們來看一個程式碼示例,看看當 getSelectionStyles 方法傳遞不同的值時的日誌輸出。在這種情況下,日誌輸出將包含第 4 個和第 5 個索引處的字元樣式。

<!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 getSelectionStyles method and passing different values</h2> <p>You can open console from dev tools and see that the 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 a text object var text = new fabric.Text("Add sample
text here"
, { width: 300, fill: "green", fontWeight: "bold", styles: { 0: { 5: { fontSize: 55, fill: "blue", fontStyle: "oblique", }, 4: { fontSize: 45, fill: "pink", fontWeight: "bold", }, }, }, }); // Add it to the canvas canvas.add(text); // Using getSelectionStyles method console.log("The style is", text.getSelectionStyles(4, 6, true)); </script> </body> </html>

更新於:2022年9月14日

696 次瀏覽

啟動您的 職業生涯

完成課程獲得認證

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