如何使用FabricJS使多边形对象对缩放事件做出反应
我们可以通过创建一个fabric.Polygon的实例来创建一个Polygon对象。一个多边形对象可以被描述为由一组连接的直线段组成的任何封闭形状。由于它是FabricJS的基本元素之一,我们也可以通过应用角度、不透明度等属性来轻松定制它。我们使用scaling事件来演示多边形对象对被缩放的反应。
语法
polygon.on(“scaling”, callbackFunction);
例1:显示对象如何对缩放事件做出反应
让我们看一个代码例子,当scaling事件发生时,多边形对象是如何反应的。我们可以通过拖动任何一个角落的控件来缩放对象。这里,当对象被缩放时,缩放事件将被连续触发。
<!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 the scaling event</h2>
<p>
You can scale the polygon object and open the console from dev tools to see the logged output
</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: 3,
objectCaching: false,
}
);
// Adding it to the canvas
canvas.add(polygon);
// Using the scaling event
polygon.on("scaling", () => {
canvas.renderAll();
console.log("The object is being scaled");
});
</script>
</body>
</html>
例子2:当缩放发生时改变笔触颜色
让我们看一个代码例子来了解当scaling事件发生时,我们如何改变笔画的颜色。我们使用set方法将多边形的笔触颜色设置为 “橙色”。因此,当我们缩放该对象时,它的笔触颜色将变为橙色。
<!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>Changing the stroke colour when scaling happens</h2>
<p>
You can see that the stroke colour changes when the polygon is scaled
</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: 500, y: 20 },
{ x: 550, y: 60 },
{ x: 550, y: 200 },
{ x: 350, y: 200 },
{ x: 350, y: 60 },
{ x: 500, y: 20 },
],
{
fill: "red",
stroke: "blue",
strokeWidth: 5,
objectCaching: false,
top: 50,
left: 30,
scaleX: 0.5,
scaleY: 0.5
}
);
// Adding it to the canvas
canvas.add(polygon);
// Using the scaling event
polygon.on("scaling", () => {
polygon.set("stroke", "orange")
canvas.renderAll();
});
</script>
</body>
</html>
结论
在本教程中,我们用两个简单的例子来演示如何使用FabricJS使多边形对象对缩放事件做出反应。