如何使用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放大和縮小多邊形物件。
廣告