如何使用 FabricJS 使多边形对象对选中和取消选中事件做出反应?
我们可以通过创建fabric.Polygon的实例来创建一个多边形对象。多边形对象可以由任何由一组连接的直线段组成的封闭形状来表示。由于它是 FabricJS 的基本元素之一,我们也可以通过应用角度、不透明度等属性来轻松自定义它。我们使用selected和deselected事件来演示如何使多边形对象对用户的对象选择和取消选择做出反应。
语法
polygon.on("selected", callbackFunction);
polygon.on("deselected", callbackFunction);
示例 1:显示对象如何对 selected 事件做出反应
让我们来看一个代码示例,演示如何使多边形对象对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 事件做出反应
让我们来看一个代码示例,了解如何使多边形对象对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 使多边形对象对选中和取消选中事件做出反应。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP