如何使用FabricJS使多边形对象对倾斜事件做出反应
我们可以通过创建一个fabric.Polygon的实例来创建一个Polygon对象。一个多边形对象可以被描述为由一组连接的直线段组成的任何封闭形状。由于它是FabricJS的基本元素之一,我们也可以通过应用角度、不透明度等属性来轻松定制它。我们使用skewing事件来演示多边形对象在通过控件进行倾斜时对用户的反应。
语法
polygon.on("skewing", callbackFunction);
例1:显示对象如何对倾斜事件做出反应
让我们看看多边形对象在使用skewing事件时的反应的代码例子。通过按下shift键,然后沿水平或垂直方向拖动中间的控件,使对象在水平和垂直方向上倾斜是可行的。当对象被倾斜时,倾斜事件被连续触发。
<!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 skewing event</h2>
<p>
You can keep skewing the object while the console from dev tools is open 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: 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: 2,
objectCaching: false,
}
);
// Adding it to the canvas
canvas.add(polygon);
// Using the skewing event
polygon.on("skewing", () => {
canvas.renderAll();
console.log("The polygon object is being skewed");
});
</script>
</body>
</html>
例2:发生倾斜时改变填充颜色
让我们看一个代码例子来了解我们如何在skewing事件发生时改变填充颜色。我们使用了set方法,这个setter允许我们指定我们想要改变的属性。在这里,每当我们倾斜多边形时,填充颜色就会变成 “绿色”。
<!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 fill colour when skew happens</h2>
<p>
You can see that the fill colour changes when the polygon is skewed
</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: 2,
objectCaching: false,
top: 50,
left: 30,
scaleX: 0.5,
scaleY: 0.5
}
);
// Adding it to the canvas
canvas.add(polygon);
// Using the skewing event
polygon.on("skewing", () => {
polygon.set("fill", "green")
canvas.renderAll();
});
</script>
</body>
</html>
结论
在本教程中,我们用两个简单的例子来演示如何使用FabricJS使多边形对象对倾斜事件做出反应。