问题
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:
- I click at some point and the result is
x: 197.82463543913713, y: 616.3652582594272
- zoom using mousewheel (
zoom: 3.9562617313728334
, cursor is still at the same point on the screen). - 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?
回答1:
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;
来源:https://stackoverflow.com/questions/39495082/cursor-location-after-zoom-using-svg-pan-zoom