如何使用 FabricJS 锁定文本框的垂直移动?
在本教程中,我们将学习如何使用 FabricJS 锁定文本框的垂直移动。就像我们可以在画布上指定文本框对象的的位置、颜色、不透明度和尺寸一样,我们还可以指定是否希望它只在 X 轴上移动。这可以通过使用 lockMovementY 属性来实现。
语法
new fabric.Textbox(text: String, { lockMovementY: Boolean }: Object)
参数
text − 此参数接受一个 字符串,表示我们希望在文本框内显示的文本字符串。
options (可选) − 此参数是一个 对象,它为我们的文本框提供了额外的自定义选项。使用此参数,可以更改与对象相关的许多属性,例如颜色、光标、描边宽度等等,其中 lockMovementY 就是一个属性。
选项键
lockMovementY − 此属性接受一个 布尔值。如果我们为它赋值为“true”,则对象将无法在垂直方向上移动。
示例 1
画布中文本框对象的默认行为
让我们来看一个代码示例,了解当 lockMovementY 属性未赋值为“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 or 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("If you're not confused, you're not paying attention.", { 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
将 lockMovementY 作为键并赋值为“true”
在本例中,我们将看到如何锁定文本框对象的垂直移动。通过将 lockMovementY 属性赋值为“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 lockMovementY as key with "true" value</h2> <p>Drag the Textbox across the X-axis or Y-axis and observer that movement is no longer allowed in the vertical 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("If you're not confused, you're not paying attention.", { backgroundColor: "#fffff0", width: 400, left: 110, top: 70, fill: "violet", strokeWidth: 2, stroke: "pink", textAlign: "center", lockMovementY: true, }); // Add it to the canvas canvas.add(textbox); </script> </body> </html>
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP