如何使用 FabricJS 設定文字框的填充?


在本教程中,我們將學習如何使用 FabricJS 設定文字框的填充。文字框是 FabricJS 提供的各種形狀之一。為了建立文字框,我們必須建立一個 `fabric.Textbox` 類的例項並將其新增到畫布中。就像我們可以指定畫布中文字框物件的位置、顏色、不透明度和尺寸一樣,我們也可以設定文字框物件的填充。這可以透過使用 `padding` 屬性來完成。

語法

new fabric.Textbox(text: String, { padding : Number }: Object)

引數

  • text − 此引數接受一個字串,即我們想要在文字框內顯示的文字字串。

  • options (可選) − 此引數是一個物件,它為我們的文字框提供了額外的自定義選項。使用此引數,可以更改與物件相關的許多屬性,例如顏色、游標、筆劃寬度等等,其中 `padding` 就是一個屬性。

選項鍵

  • padding − 此屬性接受一個數字值。分配的值決定了文字框物件與其控制邊界之間的距離。

示例 1

不使用填充時的預設外觀

讓我們看一個程式碼示例,該示例顯示在不使用 `padding` 屬性時文字框物件的外觀。我們可以看到,物件與其周圍的控制邊界之間沒有空格。這意味著文字框與其控制邊界之間沒有填充。

<!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>Default appearance when padding is not used</h2> <p>You can select the textbox to see there is no space between the object and its controlling borders</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("Keep a smile on your face. Keep a spring in your step.", { left: 110, top: 45, fill: "orange", stroke: "green", width: 400, }); // Add it to the canvas canvas.add(textbox); </script> </body> </html>

示例 2

傳遞padding屬性作為鍵

在這個例子中,我們傳遞 `padding` 屬性作為鍵,其值為 7。這表示文字框物件與其所有控制邊界之間將有 7px 的距離。

<!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 padding property as key</h2> <p>You can select the textbox to see the padding between the object and its controlling borders</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("Keep a smile on your face. Keep a spring in your step.", { left: 110, top: 45, fill: "orange", stroke: "green", width: 400, padding: 7, backgroundColor: "#f5f5dc", }); // Add it to the canvas canvas.add(textbox); </script> </body> </html>

更新於:2022年8月2日

544 次瀏覽

啟動你的職業生涯

完成課程獲得認證

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