snap.svg.zpd icon indicating copy to clipboard operation
snap.svg.zpd copied to clipboard

Zoom to bounding box

Open jlgrall opened this issue 10 years ago • 5 comments

Here is a function to zoom to the bounding box of an element:

// Inspired by https://gist.github.com/mbostock/4699541
var zoomToBBox = function(elem) {
        var width = svg.node.clientWidth,
            height = svg.node.clientHeight,
            minScale = zpdElement.options.zoomThreshold[0],
            maxScale = zpdElement.options.zoomThreshold[1],
            filling = 0.9,
            bbox = elem.getBBox(),
            dx = bbox.x2 - bbox.x,
            dy = bbox.y2 - bbox.y,
            x = (bbox.x + bbox.x2) / 2,
            y = (bbox.y + bbox.y2) / 2,
            realScale = filling / Math.max(dx / width, dy / height),
            scale = Math.min(Math.max(realScale, minScale), maxScale),
            translateX = width / 2 - scale * x,
            translateY = height / 2 - scale * y,
            m = Snap.matrix(scale, 0, 0, scale, translateX, translateY);
        zpd.animate({ transform: m }, 400, mina.easeout);
    };

Notes:

  • filling = 0.9: the bounding box takes at most 90% of the screen.
  • doesn't account for undefined zoomThresholds.

jlgrall avatar Nov 30 '14 05:11 jlgrall

@jlgrall It doesn't work :cry: Would you mind see this again?

hueitan avatar Jan 19 '15 07:01 hueitan

This worked for me, (please notice I removed the respect for maxScale):

function zoomToBBox(elem) {
    var zpdElement =  Snap.select('#snapsvg-zpd-'+paper.id);
    var width = paper.node.clientWidth,
        height = paper.node.clientHeight,
        filling = 0.9,
        bbox = elem.getBBox(),
        x = (bbox.x + bbox.x2) / 2,
        y = (bbox.y + bbox.y2) / 2,
        scale = filling / Math.max(bbox.w / width, bbox.h / height),
        translateX = width / 2 - scale * x,
        translateY = height / 2 - scale * y,
        m = Snap.matrix(scale, 0, 0, scale, translateX, translateY);
   zpdElement.transform(m);
    // paper.animate({ transform: m }, 400, mina.easeout);
};

justin-hackin avatar May 05 '15 20:05 justin-hackin

I created a PR for the code integrated into the plugin as seen here: https://github.com/justin-hackin/snap.svg.zpd/tree/zoomToElement

justin-hackin avatar May 06 '15 16:05 justin-hackin

when I console.log(bbox) I get {x: , y: , width: , height: } I don't see any bbox.x2, bbox.y2, bbox.w or bbox.h. Can someone explain what x2 and y2 are supposed to be?

macd2point0 avatar Jun 04 '15 19:06 macd2point0

its not working properly in mozilla firefox . can someone pls help. The rootSvg.clientWidth and rootSvg.clientHeight values are zero.

var zoomToElement = function(el, filling, overrideScale, interval, ease, cb){ var zpdElement = snapsvgzpd.dataStore[this.id].element, rootSvg = snapsvgzpd.dataStore[this.id].data.root, width = rootSvg.clientWidth, height = rootSvg.clientHeight,

deepak-thinqq avatar Jul 22 '16 06:07 deepak-thinqq