如何使用FabricJS锁定矩形的旋转?

在本教程中,我们将学习如何使用 FabricJS 锁定矩形的旋转。正如我们可以指定画布中矩形对象的位置、颜色、不透明度和尺寸一样,我们也可以指定它是否旋转。这可以通过使用 lockRotation 属性来完成。
语法
new fabric.Rect({ lockRotation : Boolean }: Object)参数
选项(可选) - 此参数是一个提供额外自定义的对象到我们的矩形。使用此参数,可以更改与 lockRotation 为属性的对象相关的颜色、光标、描边宽度等属性以及许多其他属性。
选项键
lockRotation - 此属性接受布尔值。如果我们为其指定“true”值,则对象旋转将被锁定。
示例 1
矩形的默认行为画布中的对象
让我们看一个代码示例,以了解不使用 lockRotation 属性时矩形对象的默认行为。默认情况下,我们可以逆时针或顺时针旋转矩形对象。
<!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>You can try rotating the rectangle to see the default behaviour</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
将 lockRotation 作为具有 True 值的键传递
在此示例中,我们将了解如何停止矩形的功能使用 lockRotation 属性来旋转的对象。正如我们所看到的,一旦我们尝试旋转矩形对象,就会显示不允许的光标。这意味着不再允许旋转操作。
<!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 lockRotation as key with a True value</h2>
<p>Try rotating the object and you will see a not-allowed cursor on the rotate handle</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,
lockRotation: true,
});
// Add it to the canvas
canvas.add(rect);
</script>
</body>
</html>
javascript