如何使用FabricJS使多边形对象对选定和取消选定的事件作出反应
我们可以通过创建一个fabric.Polygon的实例来创建一个Polygon对象。一个多边形对象可以被描述为由一组连接的直线段组成的任何封闭形状。由于它是FabricJS的基本元素之一,我们也可以通过应用角度、不透明度等属性来轻松定制它。我们使用selected和deselected事件来演示如何使多边形对象对用户的选择和取消选择作出反应。
语法
polygon.on("selected", callbackFunction);
polygon.on("deselected", callbackFunction);
例1:显示对象如何对选定的事件做出反应
让我们看看如何使多边形对象对selected事件作出反应的代码示例。点击该对象将触发selected事件,执行回调函数。在这种情况下,只要我们点击多边形对象,它的填充颜色就会改变,并显示一个记录的输出。
<!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 selected event</h2>
<p>Select the object to see the event callback function fired</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: "black",
stroke: "blue",
strokeWidth: 2,
objectCaching: false,
}
);
// Adding it to the canvas
canvas.add(polygon);
// Using the selected event
polygon.on("selected", () => {
polygon.fill = "blue";
canvas.renderAll();
console.log("The polygon object is selected");
});
</script>
</body>
</html>
例2:显示对象如何对取消选择的事件做出反应
让我们看一个代码例子来了解如何使多边形对象对deselected事件做出反应。在这里,一旦多边形对象被取消选择,该事件就会被触发,从而改变填充颜色。
<!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 deselected event</h2>
<p>Deselect the object to see the event callback function fired</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 deselected event
polygon.on("deselected", () => {
polygon.fill = "black";
canvas.renderAll();
console.log("The polygon object is deselected");
});
</script>
</body>
</html>
结论
在本教程中,我们用两个简单的例子来演示如何使用FabricJS使多边形对象对选定和取消选定的事件做出反应。