我们可以通过创建fabric.Polygon的实例来创建一个Polygon对象。多边形对象的特征可以是由一组连接的直线段组成的任何闭合形状。由于它是 FabricJS 的基本元素之一,我们还可以通过应用角度、不透明度等属性轻松自定义它。我们使用 scaling 事件来演示多边形对象如何对缩放做出反应。
语法
polygon.on(“scaling”, callbackFunction);
示例 1:显示对象如何响应缩放事件
让我们看一个代码示例,了解当缩放事件发生时多边形对象如何反应。我们可以通过拖动任何角控件来缩放对象。这里,当对象被缩放时,缩放事件将被连续触发。
<!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 scaling event</h2> <p> You can scale the polygon object and open the console from dev tools 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: 0, y: 0 }, { x: 0, y: 50 }, { x: 50, y: 50 }, { x: 50, y: 0 }, ], { left: 100, top: 30, fill: "red", stroke: "blue", strokeWidth: 3, objectCaching: false, } ); // Adding it to the canvas canvas.add(polygon); // Using the scaling event polygon.on("scaling", () => { canvas.renderAll(); console.log("The object is being scaled"); }); </script> </body> </html>
示例 2:缩放时更改描边颜色
让我们看一个代码示例,以了解如何在发生缩放事件时更改描边颜色。我们使用 set 方法将多边形的描边颜色设置为“橙色”。因此,当我们缩放对象时,其描边颜色将变为橙色。
<!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 stroke colour when scaling happens</h2> <p> You can see that the stroke colour changes when the polygon is scaled </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: 5, objectCaching: false, top: 50, left: 30, scaleX: 0.5, scaleY: 0.5 } ); // Adding it to the canvas canvas.add(polygon); // Using the scaling event polygon.on("scaling", () => { polygon.set("stroke", "orange") canvas.renderAll(); }); </script> </body> </html>
结论
在本教程中,我们使用两个简单的示例来演示如何使用 FabricJS 使多边形对象对缩放事件做出反应。
以上就是如何使用 FabricJS 使多边形对象对缩放事件做出反应?的详细内容,更多请关注编程之家其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。