0

I have an svg map with a g element container. inside the g element I have items with x, y positions.

I am trying to implement a mouse wheel zoom that pans the g element so that the object under the mouse is always under the mouse. similar to the way Google maps pans the map when zooming via the mouse wheel so that you zoom to the mouse position.

I have exhausted all searches and tried many different ways to calculate out the mouse position verses the g element position.

I've tried:

var xPan = (mouse.x - (matrix.scale * mouse.x)) - matrix.panX;
var yPan = (mouse.y - (matrix.scale * mouse.y)) - matrix.panY;
pan(xPan, yPan);
000
  • 26,951
  • 10
  • 71
  • 101
user2213022
  • 21
  • 1
  • 3
  • 1
    Can you post the most promising of the "many different ways" you tried, so we can try from that angle? – 000 Mar 26 '13 at 19:11
  • var xPan = (mouse.x - (matrix.scale * mouse.x)) - matrix.panX; var yPan = (mouse.y - (matrix.scale * mouse.y)) - matrix.panY; pan(xPan, yPan);//function transforms the matrix x and y – user2213022 Mar 26 '13 at 19:48
  • I've edited your question. Please edit it again with more helpful code. – 000 Mar 26 '13 at 19:49
  • Very similar: http://stackoverflow.com/questions/5189968/zoom-canvas-to-mouse-cursor The math is the same as in that interactive demo, you just apply it to SVG instead of canvas. – Phrogz Mar 27 '13 at 15:44

1 Answers1

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

Community
  • 1
  • 1
Kevkong
  • 460
  • 3
  • 16