Search code examples
javascriptsvgzoomingpansvgpanzoom

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;

calculation

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


Solution

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