1

I'm using svg-pan-zoom library and I need to pan/zoom the view to fit a particular element. I could use fit method but it fits the whole content in this case I need to fit only one particular element. Another option can be to calculate the pan and zoom required and use the custom control, but how to get the pan/zoom of an element to fit the window?

UPDATE

I tried to follow the @bumbu "easier" solution. That was my first thought but I have encountered some troubled with the zooming point position.

This is a fiddle to show the expected behaviour and the calculation attempt.

http://jsfiddle.net/mgv5fuyw/2/

this is the calculation:

var bb=$("#target")[0].getBBox();
var x=bb.x+bb.width/2;
var y=bb.y+bb.height/2;

calculation

But somehow the zooming center expected (225,225) is not the right one.

Tobia
  • 9,165
  • 28
  • 114
  • 219
  • Related question: https://stackoverflow.com/questions/59579575/how-to-get-x-y-coordinates-from-path-element-inside-svg – Sphinxxx Mar 05 '20 at 16:03
  • Thanks, but this is requesting only how to get a constant coordinate of clicked element. In my case I need to zoom but I don't know how to get the right zoom/pan values to fit the desidered element – Tobia Mar 05 '20 at 16:58

2 Answers2

2

I found a solution panning before zooming, I could not find the right way to use zoomAtPoint() method.

http://jsfiddle.net/mgv5fuyw/3/

var bb=$("#target")[0].getBBox();
var vbb=panZoomInstance.getSizes().viewBox;
var x=vbb.width/2-bb.x-bb.width/2;
var y=vbb.height/2-bb.y-bb.height/2;
var rz=panZoomInstance.getSizes().realZoom;
var zoom=vbb.width/bb.width;
panZoomInstance.panBy({x:x*rz,y:y*rz});
panZoomInstance.zoom(zoom);
Tobia
  • 9,165
  • 28
  • 114
  • 219
0

Without going into detail I'd try 2 approaches:

Easier:

  • Init the svg-pan-zoom library
  • Fit and center you SVG
  • Calculate positions (top-left and bottom-right, or center and size) of the elements you're interested in
  • Now based on viewport size you should be able to calculate zoom level and center point of each element

Harder:

  • Figure out relative position of the original objects relative to original viewport
  • Based on current viewport size you should be able to calculate zoom level and center point of each element
bumbu
  • 1,297
  • 11
  • 29
  • Thank you, the easier way was my first attemp. But I had some trouble with the zooming point coordinates. I have updated the question. – Tobia Mar 07 '20 at 09:14