如何使用 FabricJS 檢查 IText 物件是否填充?


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

但是,基於 IText 的文字框允許我們調整文字矩形的大小並自動換行。對於 IText 來說,情況並非如此,因為高度不會根據行的換行進行調整。我們可以使用各種屬性來操作我們的 IText 物件。同樣,我們可以使用 hasFill 方法檢查 IText 物件是否已填充。

語法

hasFill()

示例 1

使用透明填充時使用 hasFill 方法

讓我們看一個程式碼示例,以檢視使用hasFill 方法以及透明填充時記錄的輸出。如果物件具有填充顏色,則hasFill 方法返回 true 值。在本例中,我們已將填充顏色設定為“transparent”。因此,記錄的輸出將為 false。

<!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 hasFill method when transparent fill is used</h2> <p>You can open console from dev tools and see that the logged output is false</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.
Lorem ipsum dolor sit amet"
,{ width: 300, left: 60, top: 70, fill: "transparent", fontStyle: "bold", backgroundColor: "#f8f4ff", stroke: "black", } ); // Add it to the canvas canvas.add(itext); // Using the hasFill method console.log("The value is: ", itext.hasFill()); </script> </body> </html>

示例 2

使用 hasFill 方法

讓我們看一個程式碼示例,以檢視使用hasFill 方法時記錄的輸出。在這種情況下,將返回 true 值,因為 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>Using the hasFill 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 an itext object var itext = new fabric.IText( "Add Sample Text Here
Lorem ipsum
dolor sit amet"
,{ width: 300, left: 60, top: 70, fill: "#b666d2", fontStyle: "bold", backgroundColor: "#f8f4ff", stroke: "black", } ); // Using the hasFill method console.log("The value is: ", itext.hasFill()); // Add it to the canvas canvas.add(itext); </script> </body> </html>

更新於: 2022年9月12日

152 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.