如何使用 FabricJS 檢查 IText 物件是否具有描邊?


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

然而,基於 IText 的文字框允許我們調整文字矩形的大小並自動換行。這對於 IText 來說並不適用,因為高度不會根據換行進行調整。我們可以使用各種屬性來操作 IText 物件。同樣,我們可以使用 hasStroke 方法檢查 IText 物件是否具有描邊。

語法

hasStroke()

示例 1

使用 hasStroke 方法時使用透明描邊

讓我們來看一個程式碼示例,看看在使用 hasStroke 方法以及透明描邊時,IText 物件中的日誌輸出。如果物件具有描邊顏色,則 hasStroke 方法返回 true 值。在本例中,我們已將 stroke 屬性的值設定為“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 hasStroke method when transparent stroke is used</h2> <p>You can open console from dev tools and see that the value being displayed in the console 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: "#b666d2", fontStyle: "bold", backgroundColor: "#f8f4ff", stroke: "transparent", } ); // Add it to the canvas canvas.add(itext); // Using the hasStroke method console.log("The value is: ", itext.hasStroke()); </script> </body> </html>

示例 2

使用 hasStroke 方法

讓我們來看一個程式碼示例,看看使用 hasStroke 方法時的日誌輸出。在這種情況下,將返回 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 hasStroke 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 hasStroke method console.log("The value is: ", itext.hasStroke()); // Add it to the canvas canvas.add(itext); </script> </body> </html>

更新於:2022年9月12日

瀏覽量:118

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告