如何使用 FabricJS 隱藏文字框?
在本教程中,我們將學習如何使用 FabricJS 隱藏文字框。文字框是 FabricJS 提供的各種形狀之一。我們可以自定義、拉伸或移動文字框中的文字。為了建立文字框,我們必須建立一個 `fabric.Textbox` 類的例項並將其新增到畫布上。我們的文字框物件可以透過多種方式進行自定義,例如更改其尺寸、新增背景顏色或使其可見或不可見。我們可以使用 `visible` 屬性來實現這一點。
語法
new fabric.Textbox(text: String, { visible: Boolean }: Object)
引數
text − 此引數接受一個字串,即我們想要在文字框內顯示的文字字串。
options (可選) − 此引數是一個物件,它為我們的文字框提供額外的自定義選項。使用此引數,可以更改與物件相關的許多屬性,其中 `visible` 屬性也是其中之一,例如顏色、游標、描邊寬度等等。
選項鍵
visible: 此屬性接受一個布林值,允許我們將物件渲染到畫布上。其預設值為 true。
示例 1
將visible 屬性作為鍵,值為 "true"
讓我們來看一個程式碼示例,瞭解當我們將 `visible` 屬性設定為 true 值時會發生什麼。透過將其賦值為 "true",我們確保我們的文字框物件被渲染到畫布上。這也是 FabricJS 的預設行為。
<!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>Passing visible property as key with a "true" value</h2> <p>You can see the textbox object has been rendered onto the canvas</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 textbox object var textbox = new fabric.Textbox("A smooth sea never made a skillful sailor.", { backgroundColor: "#fffff0", width: 400, left: 110, top: 70, fill: "violet", strokeWidth: 2, stroke: "blue", textAlign: "center", visible: true, }); // Add it to the canvas canvas.add(textbox); </script> </body> </html>
示例 2
將visible 屬性作為鍵,值為 "false"
在這個例子中,我們將 `visible` 屬性作為鍵,值為 false。賦值為 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>Passing visible property as key with a "false" value</h2> <p>You can see the textbox object has not been rendered onto the canvas</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 textbox object var textbox = new fabric.Textbox("A smooth sea never made a skillful sailor.", { backgroundColor: "#fffff0", width: 400, left: 110, top: 70, fill: "violet", strokeWidth: 2, stroke: "blue", textAlign: "center", visible: false, }); // Add it to the canvas canvas.add(textbox); </script> </body> </html>
廣告