如何使用 FabricJS 锁定文本框的水平倾斜?
fabricjshtml5 canvasjavascript
在本教程中,我们将学习如何使用 FabricJS 锁定文本框的水平倾斜。就像我们可以在画布中指定文本框对象的位置、颜色、不透明度和尺寸一样,我们也可以指定是否要停止水平倾斜对象。这可以通过使用 lockSkewingX 属性来实现。
语法
new fabric.Textbox(text: String, { lockSkewingX : Boolean }: Object)
参数
text − 此参数接受一个 String,这是我们想要在文本框内显示的文本字符串。
options (可选) − 此参数是一个 Object,它为我们的文本框提供额外的自定义。使用此参数,可以更改与具有 lockSkewingX 属性的对象相关的属性(例如颜色、光标、笔触宽度和许多其他属性)。
选项键
lockSkewingX −此属性接受 布尔 值。如果我们为其分配"true"值,则对象的水平倾斜将被锁定。
示例 1
画布中文本框对象的默认行为
让我们看一个代码示例,以了解未使用 lockSkewingX 属性时文本框对象的默认行为。按住 Shift 键,然后沿水平或垂直方向拖动,即可在水平和垂直方向上倾斜对象。
<!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 press the shift-key and drag the edge along the X or Y-axis to see that skewing 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("The eyes are useless when the mind is blind.", { width: 400, left: 110, top: 70, fill: "orange", strokeWidth: 2, stroke: "green", textAlign: "center", }); // 将其添加到画布 canvas.add(textbox); </script> </body> </html>
示例 2
将 lockSkewingX 作为键传递,值为"true"
在此示例中,我们将看到如何使用 lockSkewingX 属性停止 Textbox 对象水平倾斜的能力。如我们所见,虽然我们可以垂直倾斜文本框对象,但不允许水平执行相同的操作。
<!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 lockSkewingX as key with ‘true’ value</h2> <p>You can try and see that skewing along the x-axis is no longer feasible</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("The eyes are useless when the mind is blind.", { width: 300, left: 110, top: 70, fill: "orange", strokeWidth: 2, stroke: "green", textAlign: "center", lockSkewingX: true, }); // 将其添加到画布 canvas.add(textbox); </script> </body> </html>