如何使用FabricJS使多边形对象对鼠标事件做出反应
我们可以通过创建一个fabric.Polygon的实例来创建一个Polygon对象。一个多边形对象可以被描述为由一组连接的直线段组成的任何封闭形状。由于它是FabricJS的基本元素之一,我们也可以通过应用角度、不透明度等属性来轻松定制它。我们使用mouseup和mousedown事件来演示多边形对象如何对用户触发的鼠标事件做出反应。
语法
polygon.on(“mouseup”, callbackFunction);
polygon.on(“mousedown”, callbackFunction);
例1:显示对象如何对鼠标上移事件作出反应
让我们看看多边形对象在触发mouseup事件时的反应的代码示例。当用户释放鼠标左键时,会发生一个mouseup事件。在这里,一旦mouseup事件被触发,笔画宽度就会变为33。
<!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 mouseup event</h2>
<p>
You can select the object and release the left mouse button to see that the stroke width has changed
</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,
objectCaching: false,
}
);
// Adding it to the canvas
canvas.add(polygon);
// Using the mouseup event
polygon.on("mouseup", () => {
polygon.set("strokeWidth", 33);
canvas.renderAll();
});
</script>
</body>
</html>
例2:显示对象如何对mousedown事件做出反应
让我们看一个代码例子,看看当mousedown事件被触发时,多边形对象如何反应。当用户按下一个按钮时,会发生mousedown事件。在这里,我们可以看到该对象对mousedown事件的反应是将其笔画宽度从33改为2。
<!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 mousedown event</h2>
<p>
You can press the left mouse button to trigger the mousedown event to see that the stroke width has changed
</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: 33,
objectCaching: false,
}
);
// Adding it to the canvas
canvas.add(polygon);
// Using the mousedown event
polygon.on("mousedown", () => {
polygon.set("strokeWidth", 2);
canvas.renderAll();
});
</script>
</body>
</html>
结论
在本教程中,我们用两个简单的例子来演示如何使用FabricJS使多边形对象对鼠标事件做出反应。