如何使用FabricJS使多边形对象放大和缩小
我们可以通过创建一个fabric.Polygon的实例来创建一个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使多边形对象放大和缩小。