javascript/canvas,地图样式点缩放

Nex*_*rem 2 javascript canvas

我有一张画布,上面有一堆物体。我有一个缩放函数,可以增加一个zoom变量,每个坐标都乘以该变量。

我希望能够指向一个坐标并对其进行缩放,类似于在线地图的操作方式。

我在这里设置了一个演示,展示了我的代码的当前状态。

Bli*_*n67 7

坐标处的比例

如果给定的屏幕坐标已缩放内容,您需要将原点移向或远离该点,移动量与缩放相匹配。

如果放大,原点将移向鼠标的位置。并缩小。

因此,使用鼠标获取 x、y 位置,并根据滚轮方向获取放大或缩小的量

// e is the mouse wheel event
const x = e.offsetX;
const y = e.offsetY;
const amount = e.wheelDelta > 0 ?  1.1 : 1 / 1.1; 
Run Code Online (Sandbox Code Playgroud)

然后将其应用到当前比例并移动原点以匹配

scale *= amount;  // the new scale
// move the origin
origin.x = x - (x - origin.x) * amount;
origin.y = y - (y - origin.y) * amount;
Run Code Online (Sandbox Code Playgroud)

然后您可以使用以下命令设置 2D 位置和比例

ctx.setTransform(scale, 0, 0, scale, origin.x, origin.y);
Run Code Online (Sandbox Code Playgroud)

例子

下面是一个简单的视图示例,使用了小提琴中的一些代码。

该对象view跟踪当前视图并维护可应用于画布的矩阵。

// e is the mouse wheel event
const x = e.offsetX;
const y = e.offsetY;
const amount = e.wheelDelta > 0 ?  1.1 : 1 / 1.1; 
Run Code Online (Sandbox Code Playgroud)
scale *= amount;  // the new scale
// move the origin
origin.x = x - (x - origin.x) * amount;
origin.y = y - (y - origin.y) * amount;
Run Code Online (Sandbox Code Playgroud)
ctx.setTransform(scale, 0, 0, scale, origin.x, origin.y);
Run Code Online (Sandbox Code Playgroud)