bumbu / svg-pan-zoom

JavaScript library that enables panning and zooming of an SVG in an HTML document, with mouse events or custom JavaScript hooks
https://github.com/ariutta/svg-pan-zoom#demos
BSD 2-Clause "Simplified" License
1.74k stars 390 forks source link

show node feature (request+ simple implementation) #381

Open Iftahh opened 4 years ago

Iftahh commented 4 years ago

I needed this feature so implemented it myself, I don't have the time to do a proper pull-request - so I'm dropping it here if someone needs something similar, or wants to pick-up the work and do a PR.

    function showNode(node) {
            const bbox = node.getBBox();

            // pan so the node is at the center
            const { width, height, realZoom } = this.getSizes()
            this.pan({
              x: -realZoom * (bbox.x - width / (realZoom * 2) + bbox.width / 2),
              y: -realZoom * (bbox.y - height / (realZoom * 2) + bbox.height / 2)
            })

            // we want to zoom in to see just around the node -
            const relativeZoom = this.getZoom();
             // this formula below could be improved... I found it worked nicely for my usecases but maybe it should controlled by a 2nd parameter to this function
            const desiredWidth = 50 * Math.sqrt(bbox.width / 25) * 11 * realZoom;   
            this.zoom(relativeZoom * width / desiredWidth)
     }
rmelchner commented 2 years ago

+1 this is such a nice feature

ItsLefty commented 4 months ago

Hi there! Can anybody tell me how to use the function above? I'm still learning JavaScript. I have a SVG mind map with a bunch of groups. On click of each groups its children are revealed. Now I want to use this function in order to center the clicked group. So I have copied the code above into my JS, then on the event-click-handler of the group I call shownode(); Sadly it is not working and in the console it says: Cannot read properties of undefined (reading 'getBBox')

Any help would be appreciated! :)