如何使用 FabricJS 使多边形对象对鼠标事件做出反应?


我们可以通过创建fabric.Polygon的实例来创建一个多边形对象。多边形对象可以由任何由一组连接的直线段组成的封闭形状来表征。由于它是 FabricJS 的基本元素之一,因此我们也可以通过应用角度、不透明度等属性来轻松自定义它。我们使用mouseupmousedown事件来演示多边形对象如何对用户触发的鼠标事件做出反应。

语法

polygon.on(“mouseup”, callbackFunction);
polygon.on(“mousedown”, callbackFunction);

示例 1:显示对象如何对 mouseup 事件做出反应

让我们来看一个代码示例,说明当触发mouseup事件时多边形对象如何做出反应。当用户释放鼠标左键时,会发生mouseup事件。在这里,一旦触发mouseup事件,笔触宽度就会更改为 33。

Open Compiler
<!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>

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

示例 2:显示对象如何对 mousedown 事件做出反应

让我们来看一个代码示例,说明当触发mousedown事件时多边形对象如何做出反应。当用户按下按钮时,会发生mousedown事件。在这里,我们可以看到对象通过将其笔触宽度从 33 更改为 2 来对 mousedown 事件做出反应。

Open Compiler
<!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 使多边形对象对鼠标事件做出反应。

更新于: 2023年1月2日

581 次浏览

开启你的 职业生涯

通过完成课程获得认证

立即开始
广告