如何使用FabricJS设置矩形允许的最小比例值?

在本教程中,我们将学习如何设置矩形的最小允许比例 使用 FabricJS。矩形是 FabricJS 提供的各种形状之一。为了 要创建一个矩形,我们必须创建一个 Fabric.Rect 类的实例并添加它 到画布。
我们可以通过添加填充颜色来自定义矩形对象,消除其边框,甚至更改其尺寸。同样,我们还可以使用 minScaleLimit 属性来设置其允许的最小比例。
语法
new fabric.Rect({ minScaleLimit : Number }: Object)参数
选项(可选) - 此参数是一个对象,它为我们的矩形提供额外的自定义。使用此参数,可以更改与 minScaleLimit 为属性的对象相关的颜色、光标、边框宽度和许多其他属性等属性。
选项键
minScaleLimit - 此属性允许我们控制矩形的最小允许比例值。它接受数字作为值。
示例 1
矩形对象的默认外观 strong>
让我们看一个代码示例,看看不使用 minScaleLimit 属性时矩形对象的样子。在这种情况下,我们将能够自由缩放对象,因为没有设置最小限制。
<!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 appearance of the rectangle object</h2>
<p>You can try scaling the rectangle to see that there is no minimum allowed scale value.</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: 155,
top: 90,
width: 170,
height: 70,
fill: "#6f2da8",
padding: 9,
stroke: "#b666d2",
strokeWidth: 5,
});
// Add it to the canvas
canvas.add(rect);
</script>
</body>
</html>示例 2
将 minScaleLimit 属性作为带有自定义值的键传递
在此示例中,我们将看到为 minScaleLimit 属性赋值如何更改画布中矩形对象的最小允许比例值。这里我们使用 0.8 作为值,这意味着我们将无法将对象缩小到小于 136 像素的宽度和 56 像素的高度,这是通过半径 * 限制计算的(0.8 * 170 = 136 像素) ,0.8 * 70 = 56 像素)。
<!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 the minScaleLimit property as key with a custom value</h2>
<p>You can try scaling the rectangle and observer that it isn't possible to scale down the rectangle lesser than a width of 136px and height of 56px.</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: 155,
top: 90,
width: 170,
height: 70,
fill: "#6f2da8",
padding: 9,
stroke: "#b666d2",
strokeWidth: 5,
minScaleLimit: 0.8,
});
// Add it to the canvas
canvas.add(rect);
</script>
</body>
</html>
javascript