0

我有一个带有 ag 元素容器的 svg 地图。在 g 元素内,我有 x、y 位置的项目。

我正在尝试实现平移 g 元素的鼠标滚轮缩放,以便鼠标下方的对象始终位于鼠标下方。类似于 Google 地图在通过鼠标滚轮缩放时平移地图的方式,以便您缩放到鼠标位置。

我已经用尽了所有搜索并尝试了许多不同的方法来计算鼠标位置与 g 元素位置。

我试过了:

var xPan = (mouse.x - (matrix.scale * mouse.x)) - matrix.panX;
var yPan = (mouse.y - (matrix.scale * mouse.y)) - matrix.panY;
pan(xPan, yPan);
4

1 回答 1

0

I had an similar problem some time ago, with the difference that I am using canvas but because I use svg to save my transform matrix it may help you, if I post the necessary part of my code:

window.transform = svg.createSVGMatrix();
window.pt = svg.createSVGPoint();

transformedPoint = function (x, y) {
    window.pt.x = x; window.pt.y = y;
    return pt.matrixTransform(window.transform.inverse());
}

translate = function(dx, dy) {
    window.transform = window.transform.translate(dx, dy);
}

scale = function (scaleX, scaleY) {
    window.transform = window.transform.scaleNonUniform(scaleX, scaleY);
};

zoom = function (scaleX, scaleY, x, y) { //use real x and y i.e. mouseposition on element
    var p = transformedPoint(x, y);
    translate(x, y);
    scale(scaleX, scaleY);
    translate(-x, -y);
}

I hope you can use some of this code and get it to work for you

Credits going to Phrogz and his outstanding example here: https://stackoverflow.com/a/5527449/1293849

于 2013-03-26T19:51:21.950 回答