如何使用FabricJS鎖定文字框的水平移動?
在本教程中,我們將學習如何使用FabricJS鎖定文字框的水平移動。就像我們可以指定畫布中文字框物件的 position、顏色、不透明度和尺寸一樣,我們也可以指定是否只想沿Y軸移動它。這可以透過使用`lockMovementX`屬性來實現。
語法
new fabric.Textbox(text: String, { lockMovementX: Boolean }: Object)
引數
text − 此引數接受一個字串,即我們想要在文字框中顯示的文字字串。
options (可選) − 此引數是一個物件,它為我們的文字框提供了額外的自定義選項。使用此引數,可以更改與物件相關的許多屬性,例如顏色、游標、描邊寬度等等,其中`lockMovementX`也是一個屬性。
選項鍵
lockMovementX − 此屬性接受一個布林值。如果我們為其賦值“true”,則該物件將無法在水平方向上移動。
示例1
畫布中文字框物件的預設行為
讓我們來看一個程式碼示例,瞭解當未為`lockMovementX`屬性賦值“true”時,我們如何自由地在X軸或Y軸上移動文字框物件。
<!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>Drag the textbox across the X-axis and Y-axis and observe that movement is allowed in both directions.</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("Time is the soul of this world.", { backgroundColor: "#fffff0", 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
將lockMovementX作為鍵,值為“true”
在這個例子中,我們將看到如何鎖定文字框物件的水平移動。透過將`lockMovementX`屬性賦值為“true”,我們實際上就阻止了水平方向的移動。
<!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 lockMovementX as key with "true" value</h2> <p>Drag the Textbox across the X-axis and Y-axis and observe that movement is no longer allowed in the horizontal 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("Time is the soul of this world.", { backgroundColor: "#fffff0", width: 400, left: 110, top: 70, fill: "violet", strokeWidth: 2, stroke: "pink", textAlign: "center", lockMovementX: "true", }); // Add it to the canvas canvas.add(textbox); </script> </body> </html>
廣告