我们可以通过创建fabric.Polygon的实例来创建一个Polygon对象。多边形对象的特征可以是由一组连接的直线段组成的任何闭合形状。由于它是 FabricJS 的基本元素之一,我们还可以通过应用角度、不透明度等属性轻松自定义它。我们使用 object:modified 事件使多边形对象对调整大小做出反应。
object:modified
让我们看一个代码示例,了解当不使用 object:modified 事件时多边形对象如何显示。在这种情况下,多边形对象将被添加到画布中。
<!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>Default appearance of the polygon object</h2> <p>You can see that the polygon object has been added to the canvas</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, } ); // Adding it to the canvas canvas.add(polygon); </script> </body> </html>
让我们看一个代码示例,以查看调整多边形对象大小时记录的输出。我们使用了 object:modified 事件,该事件在任何对象转换或与对象有关的任何更改结束时触发。在这种情况下,每次我们更改对象的比例时,缩放后的高度和宽度都会被控制台记录。
<!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 being resized</h2> <p> You can scale object using corner and open console from dev tools to see that the scaled width and height value of the polygon object is being logged </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, } ); // Adding it to the canvas canvas.add(polygon); // Using object:modified event canvas.on("object:modified", (e) => { canvas.getActiveObjects().forEach((o) => { console.log( "Scaled Height of the polygon is: ", o.getScaledHeight(), "Scaled Width of the polygon is:", o.getScaledWidth() ); }); }); </script> </body> </html>
在本教程中,我们使用两个简单的示例来演示如何使用 FabricJS 让多边形对象对调整大小事件做出反应。
以上是如何使用 FabricJS 使多边形对象对调整大小事件做出反应?的详细内容。更多信息请关注PHP中文网其他相关文章!