如何使用 FabricJS 锁定文本框的水平缩放?
fabricjshtml5 canvasjavascript
在本教程中,我们将学习如何使用 FabricJS 锁定文本框的水平缩放。就像我们可以在画布中指定文本框对象的位置、颜色、不透明度和尺寸一样,我们也可以指定是否要停止水平缩放对象。这可以通过使用 lockScalingX 属性来实现。
语法
new fabric.Textbox(text: String, { lockScalingX : Boolean }: Object)
参数
text − 此参数接受 String,这是我们想要在文本框内显示的文本字符串。
options (可选) − 此参数是一个 Object,可为我们的文本框提供额外的自定义。使用此参数,可以更改与具有 lockScalingX 属性的对象相关的属性(例如颜色、光标、笔触宽度和许多其他属性)。
选项键
lockScalingX − 此属性接受 布尔 值。如果我们为其分配"true"值,则对象的水平缩放将被锁定。
示例 1
画布中文本框对象的默认行为
让我们看一个代码示例,以了解未使用 lockScalingX 属性时文本框对象的默认行为。在水平和垂直方向上缩放对象都是可行的。
<!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 verifythat scaling is possible in both directions.</p> <canvas id="canvas"></canvas> <script> // 启动一个canvas实例 var canvas = new fabric.Canvas("canvas"); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); // 初始化一个 textbox 文本框对象 var textbox = new fabric.Textbox("Stars can’t shine without darkness.", { width: 400, left: 110, top: 70, fill: "violet", strokeWidth: 2, stroke: "pink", textAlign: "center", }); // 将其添加到画布 canvas.add(textbox); </script> </body> </html>
示例 2
将 lockScalingX 作为键传递,值为"true"
在此示例中,我们将看到如何使用 lockScalingX 属性停止文本框对象水平缩放的能力。如我们所见,虽然我们可以垂直缩放文本框对象,但不允许水平执行相同的操作。
<!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 lockScalingX as key with "true" value</h2> <p>You can see a "not-allowed" cursor if you try to scale the textbox in the X-direction </p> <canvas id="canvas"></canvas> <script> // 启动一个canvas实例 var canvas = new fabric.Canvas("canvas"); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); // 初始化一个 textbox 文本框对象 var textbox = new fabric.Textbox("Stars can't shine without darkness.", { width: 400, left: 110, top: 70, fill: "violet", strokeWidth: 2, stroke: "pink", textAlign: "center", lockScalingX: true, }); // 将其添加到画布 canvas.add(textbox); </script> </body> </html>