如何在地图应用程序中实现稳定缩放 [英] How to implement a stable zoom in a mapping application
问题描述
我正在使用与Google地图类似的点击拖动和缩放功能来实施应用。我设法实现平移和缩放,但缩放点目前在坐标 0,0
。当放大和缩小时,网格在坐标 0,0
时的位置保持固定,而其他所有坐标从此点开始放大/缩小。
I'm implementing a application with a click-and-drag and zoom functionality that is similar to Google Maps. I've managed to implement panning and zooming however, the zoom point is currently at the coordinates 0,0
. When you zoom in and out, the position of the grid at coordinates 0,0
stays fixed while all the other coordinates zoom closer/further from this point.
相反,我想能够实现一个稳定的缩放,其中缩放点是当前鼠标位置下的位置。要了解我要查找的内容,请打开Google地图,将鼠标放在特定点上方,然后使用鼠标滚轮滚动。注意鼠标下的位置是如何固定的。
Instead, I would like to be able to implement a stable zoom where the zoom point is the location under the current mouse position. To get an idea of what I'm looking for, open Google Maps, position your mouse above a particular point and use the mouse wheel to scroll. Notice how the location under your mouse stays fixed.
如何修改本示例中的 zoomGrid
鼠标滚轮缩放,它尊重鼠标的位置?
How can I modify the zoomGrid
function in this example to implement mouse wheel zooming that respects the position of the mouse?
function zoomGrid(mouseEvent) {
var delta = mouseEvent.deltaY;
if (mouseEvent.deltaMode == 1) { //Firefox scrolls by line instead of by pixel so multiply the delta by 20
delta *= 20;
}
zoom += delta;
zoom = Math.min(zoom, 3000);
zoom = Math.max(zoom, -1000);
scale = Math.pow(2,(zoom / 1000));
var mousePos = {x: mouseEvent.offsetX, y: mouseEvent.offsetY};
//gridPos = ???
drawGrid();
drawShapes();
}
完整演示: http://codepen.io/alexspurling/pen/jApazY
(PS我已经看到了 paper.js教程,但无法
(PS I've already seen the paper.js tutorial but wasn't able to translate the logic there into workable code).
推荐答案
我终于找到了解决方案后,我想到了什么是我是试图做。关键的洞察是,鼠标在网格上的位置应该在改变比例之前和之后是相同的。
I finally found the solution after some thought about exactly what it was that I was trying to do. The key insight was that the position of the mouse on the grid should be the same both before changing the scale and after.
考虑到这一点,我不得不做在缩放之前记录鼠标的位置:
With that in mind, all I had to do was record the position of the mouse before scaling:
var mousePos = {x: mouseEvent.offsetX, y: mouseEvent.offsetY};
var mouseGridPos = plus(multiply(mousePos, scale), gridPos);
然后调整比例:
var delta = mouseEvent.deltaY;
if (mouseEvent.deltaMode == 1) { //Firefox scrolls by line instead of by pixel so multiply the delta by 20
delta *= 20;
}
zoom += delta;
zoom = Math.min(zoom, 3000);
zoom = Math.max(zoom, -1000);
scale = Math.pow(2,(zoom / 1000));
然后找到新的网格位置,假设鼠标坐标位置没有改变,
Then find the new grid position assuming the position at the mouse coordinates have not changed with the new scale:
//Calculate the grid position by using the previous scaled
//mouse position and the new scale
gridPos = minus(mouseGridPos, multiply(mousePos, scale));
我已经在这里创建了一个有效缩放的新代码笔:
I've created a new Code pen with working zooming here:
http://codepen.io/alexspurling/pen/xOJJdm
这篇关于如何在地图应用程序中实现稳定缩放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!