如何使用 FabricJS 鎖定文字框的垂直縮放?


在本教程中,我們將學習如何使用 FabricJS 鎖定文字框的垂直縮放。就像我們可以在畫布上指定文字框物件的定位、顏色、不透明度和尺寸一樣,我們還可以指定是否希望停止物件的垂直縮放。這可以透過使用lockScalingY屬性來實現。

語法

new fabric.Textbox(text: String, { lockScalingY : Boolean }: Object)

引數

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

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

選項鍵

  • lockScalingY − 此屬性接受一個布林值。如果我們將其分配一個“true”值,則物件的垂直縮放將被鎖定。

示例 1

畫布中文字框物件的預設行為

讓我們看一個程式碼示例,以瞭解在不使用lockScalingY屬性時文字框物件的預設行為。可以在水平和垂直方向上縮放物件。

<!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 behaviour of a Textbox object in the canvas</h2> <p>You can scale the textbox in horizontal and vertical directions to verify that scaling in both directions is possible</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("The fool wonders, the wise man asks.", { width: 400, left: 110, top: 70, fill: "violet", strokeWidth: 2, stroke: "pink", textAlign: "center", }); // Add it to the canvas canvas.add(textbox); </script> </body> </html>

示例 2

lockScalingY作為鍵傳遞,值為“true”

在本例中,我們將看到如何使用lockScalingY屬性停止文字框物件垂直縮放的能力。如我們所見,雖然我們可以水平縮放文字框物件,但我們不允許垂直執行相同的操作。

<!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 lockScalingY as key with "true" value</h2> <p>You can see a not-allowed cursor if you try to scale the textbox in the y-direction</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("The fool wonders, the wise man asks.", { width: 400, left: 110, top: 70, fill: "violet", strokeWidth: 2, stroke: "pink", textAlign: "center", lockScalingY: true, }); // Add it to the canvas canvas.add(textbox); </script> </body> </html>

更新時間: 2022年8月2日

163 次瀏覽

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告