简体   繁体   中英

How to pan and zoom to fit an element with SvgPanZoom

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;

计算

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

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM