如何使用FabricJS缩放多边形对象?
我们可以通过创建fabric.Polygon的实例来创建一个多边形对象。多边形对象可以用任何由一组连接的直线段组成的封闭形状来表示。由于它是FabricJS的基本元素之一,我们也可以通过应用角度、不透明度等属性来轻松定制它。
语法
canvas.on("mouse:wheel", callbackFunction);
示例1:在多边形对象上应用缩放控制
让我们来看一个代码示例,说明如何在多边形对象上应用缩放控制。我们可以移动鼠标滚轮来放大或缩小。我们添加了事件监听器来监听鼠标滚动并分别使用setZoom更新缩放值。
<!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>Applying zoom controls on a Polygon object</h2> <p>You can move the mouse wheel to zoom-in or zoom-out</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: 50 }, { x: 50, y: 0 }, { x: 0, y: 0 }, ], { left: 30, fill: "#aa98a9", stroke: "#002e63", strokeWidth: 2, } ); // Adding it to the canvas canvas.add(polygon); // Using mouse:wheel event canvas.on("mouse:wheel", function (options) { // Get the wheel scroll value var delta = options.e.deltaY; // Get the current zoom value var zoom = canvas.getZoom(); // Update the current zoom value zoom = (0.999 ** delta) * zoom; // Set the current zoom value canvas.setZoom(zoom); options.e.preventDefault(); options.e.stopPropagation(); }); </script> </body> </html>
示例2:在矩形对象上应用缩放控制
让我们来看一个代码示例,了解如何在其他对象(例如矩形)中应用缩放控制。我们初始化了一个宽度为100px,高度为60px的矩形对象。我们可以移动鼠标滚轮来放大或缩小。
<!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>Applying zoom controls on a Rectangle object</h2> <p>You can move the mouse wheel to zoom-in or zoom-out</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 rectangle instance var rectangle = new fabric.Rect({ height: 60, width: 100, left: 30, fill: "#aa98a9", stroke: "#002e63", strokeWidth: 2, }); // Adding it to the canvas canvas.add(rectangle); // Using mouse:wheel event canvas.on("mouse:wheel", function (options) { // Get the wheel scroll value var delta = options.e.deltaY; // Get the current zoom value var zoom = canvas.getZoom(); // Update the current zoom value zoom = (0.999 ** delta) * zoom; // Set the current zoom value canvas.setZoom(zoom); options.e.preventDefault(); options.e.stopPropagation(); }); </script> </body> </html>
结论
在本教程中,我们使用两个简单的示例演示了如何使用FabricJS放大和缩小多边形对象。
广告