如何使用FabricJS使多边形对象对调整大小的事件做出反应
我们可以通过创建一个fabric.Polygon的实例来创建一个Polygon对象。一个多边形对象可以被描述为由一组连接的直线段组成的任何封闭形状。由于它是FabricJS的基本元素之一,我们也可以通过应用角度、不透明度等属性轻松定制它。我们使用object:modified事件来使多边形对象对被调整大小作出反应。
语法
object:modified
例1:多边形对象的默认外观
让我们看一个代码例子,当不使用object:modified事件时,多边形对象如何出现。在这种情况下,多边形对象将被添加到画布上。
<!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 polygon object</h2>
<p>You can see that the polygon object has been added to the canvas</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 polygon instance
var polygon = new fabric.Polygon(
[
{ x: 0, y: 0 },
{ x: 0, y: 50 },
{ x: 50, y: 50 },
{ x: 50, y: 0 },
],
{
left: 100,
top: 30,
fill: "red",
stroke: "blue",
strokeWidth: 2,
}
);
// Adding it to the canvas
canvas.add(polygon);
</script>
</body>
</html>
例2:显示对象对被调整大小的反应
让我们看一个代码例子,看看多边形对象被调整大小时的记录输出。我们使用了object:modified事件,该事件在任何对象转换或有关对象的任何变化结束时触发。在这种情况下,每当我们改变对象的比例时,比例的高度和宽度将被控制台记录下来。
<!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>Displaying how the object reacts to being resized</h2>
<p>
You can scale object using corner and open console from dev tools to see that the scaled width and height value of the polygon object is being logged
</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 polygon instance
var polygon = new fabric.Polygon(
[
{ x: 0, y: 0 },
{ x: 0, y: 50 },
{ x: 50, y: 50 },
{ x: 50, y: 0 },
],
{
left: 100,
top: 30,
fill: "red",
stroke: "blue",
strokeWidth: 2,
}
);
// Adding it to the canvas
canvas.add(polygon);
// Using object:modified event
canvas.on("object:modified", (e) => {
canvas.getActiveObjects().forEach((o) => {
console.log(
"Scaled Height of the polygon is: ",
o.getScaledHeight(),
"Scaled Width of the polygon is:",
o.getScaledWidth()
);
});
});
</script>
</body>
</html>
结论
在本教程中,我们用两个简单的例子来演示如何使用FabricJS使多边形对象对大小调整事件做出反应。