如何使用 FabricJS 從頂部設定文字框的位置?
在本教程中,我們將學習如何使用 FabricJS 從頂部設定文字框的位置。`top` 屬性允許我們操作物件的位置。我們可以自定義、拉伸或移動文字框中的文字。為了建立文字框,我們必須建立一個 `fabric.Textbox` 類的例項並將其新增到畫布。預設情況下,頂部位置相對於畫布的頂部邊緣。
語法
new fabric.Textbox(text: String, { top: Number }: Object)
引數
text − 此引數接受一個字串,即我們想要在文字框內顯示的文字字串。
options (可選) − 此引數是一個物件,它為我們的文字框提供額外的自定義選項。使用此引數,可以更改與物件相關的許多屬性,其中 `top` 是一個屬性,例如顏色、游標、描邊寬度等。
選項鍵
top:此屬性接受一個數字,允許我們設定文字框距畫布頂部的距離。
示例 1
文字框物件的預設外觀
讓我們來看一個程式碼示例,瞭解當不使用 `top` 屬性時,文字框物件的外觀。
<!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 of the Textbox object</h2> <p>You can see the default appearance of Textbox in this example</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("Tomorrow is often the busiest day of the week.", { backgroundColor: "#e3dac9", width: 400, left: 70, fill: "green", stroke: "black", }); // Add it to the canvas canvas.add(textbox); </script> </body> </html>
示例 2
將 `top` 屬性作為鍵,並帶有自定義值
在這個示例中,我們將 `top` 屬性作為鍵,其值為 70。這意味著我們的文字框物件將放置在距頂部 70px 的距離。
<!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 the top property as key with a custom value</h2> <p>You can see that now the textbox is placed at a distance of 70px from the top</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("Tomorrow is often the busiest day of the week.", { backgroundColor: "#e3dac9", width: 400, left: 70, top: 70, fill: "green", stroke: "black", }); // Add it to the canvas canvas.add(textbox); </script> </body> </html>
廣告