如何使用 FabricJS 设置矩形的最小允许缩放值?
在本教程中,我们将学习如何使用 FabricJS 设置矩形的最小允许缩放值。矩形是 FabricJS 提供的各种形状之一。为了创建一个矩形,我们将必须创建一个fabric.Rect类的实例并将其添加到画布中。
我们可以通过添加填充颜色、消除其边框甚至更改其尺寸来自定义矩形对象。同样,我们也可以使用minScaleLimit属性设置其最小允许缩放值。
语法
new fabric.Rect({ minScaleLimit : Number }: Object)参数
选项(可选) - 此参数是一个对象,它为我们的矩形提供额外的自定义设置。使用此参数,可以更改与对象的许多属性相关的属性,其中minScaleLimit就是一个属性,例如颜色、光标、边框宽度等。
选项键
minScaleLimit - 此属性允许我们控制矩形的最小允许缩放值。它接受一个数字作为值。
示例 1
矩形对象的默认外观
让我们来看一个代码示例,看看当不使用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>
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP