如何使用 FabricJS 锁定矩形的垂直移动?
在本教程中,我们将学习如何使用 FabricJS 锁定矩形的垂直移动。就像我们可以在画布中指定矩形对象的的位置、颜色、不透明度和尺寸一样,我们还可以指定是否希望它仅在 X 轴上移动。这可以通过使用lockMovementY 属性来实现。
语法
new fabric.Rect({ lockMovementY: Boolean }: Object)参数
options(可选) - 此参数是一个对象,它为我们的矩形提供了额外的自定义选项。使用此参数,可以更改与对象相关的许多属性,例如颜色、光标、描边宽度以及 borderDashArray 属性。
选项键
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 Rectangle object in the canvas</h2>
<p>Drag the rectangle across the X-axis and Y-axis to see 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 rectangle object
var rect = new fabric.Rect({
left: 55,
top: 90,
width: 170,
height: 70,
fill: "black",
padding: 9,
stroke: "#483d8b",
strokeWidth: 5,
});
// Add it to the canvas
canvas.add(rect);
</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>Default behaviour of a Rectangle object in the canvas</h2>
<p>Drag the rectangle across the X-axis and Y-axis to see that the 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 rectangle object
var rect = new fabric.Rect({
left: 55,
top: 90,
width: 170,
height: 70,
fill: "black",
padding: 9,
stroke: "#483d8b",
strokeWidth: 5,
lockMovementY: true,
});
// Add it to the canvas
canvas.add(rect);
</script>
</body>
</html>
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP