如何使用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>

更新于:2022年8月2日

浏览量:110

启动您的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.