javascriptsvgsvgpanzoom

Cursor location after zoom using svg-pan-zoom


I am using the ariutta svg-pan-zoom library. I have a SVG file with viewBox="0 0 1052.3622 744.09448" and div container with width=649 and heigth=525,59. I'm trying to get cursor location inside my SVG.

My code:

var divX = ev.pageX - this.offsetLeft;
var divY = ev.pageY - this.offsetTop;

var currentPan = panZoom.getPan();
var realZoom = panZoom.getSizes().realZoom;
var panZoomHeight = panZoom.getSizes().height;
var viewboxHeight = panZoom.getSizes().viewBox.height;

var x = (divX - currentPan.x) / realZoom;
var y = ((panZoomHeight - divY - ((panZoomHeight-(viewboxHeight*realZoom))/2) + currentPan.y) / realZoom);

var zoom = panZoom.getZoom(); // only to explain my problem - I'm not using this value 

It works fine until zoom equals 1 (default zoom level). When zoom is greater than 1 the y value is wrong (x is good). For example:

  1. I click at some point and the result is x: 197.82463543913713, y: 616.3652582594272
  2. zoom using mousewheel (zoom: 3.9562617313728334, cursor is still at the same point on the screen).
  3. click again and the result is x: 197.82463192575807, y: 540.7407139122004

I've been trying many combinations of code, but nothing works good. I have no idea how to do this. Am I missing something obvious? Is there any better solution to get cursor position?


Solution

  • I'm an idiot! I had a bug in the other part of my code. That is why I thought that the y value was correct for zoom == 1 - in fact it wasn't.

    This works for me:

    var y = (panZoomHeight - divY - (panZoomHeight-(viewboxHeight*realZoom)) + currentPan.y) / realZoom;