Search code examples
javascriptsvgviewbox

Svg zoom to specific rect


I have SVG with multiple grouped elements. What I to do is to zoom to secific group.

I already got rect with {top, left, width, height} that I would like to zoom to (change viewBox attribute of my SVG).

Any easy way to calculate the right values for the viewBox?


Solution

  • You can set the viewBox to equal "top left width height":

    Here's a simple example. Clicking on either rectangle will zoom the screen on that rectangle. Clicking on it again will return the screen to its original zoom.

    var selected = false;
    var svg = document.getElementById('svg');
    
    var zoomOnElement = function(e) {
        if (e.target === selected) {
    	// Deselect element
    	svg.setAttribute("viewBox", "0 0 600 400");
    	selected = false;
        } else {
    	// Select element
    	selected = e.target;
    	var viewBox = selected.getAttribute('x');
    	viewBox += " " + selected.getAttribute('y')
    	viewBox += " " + selected.getAttribute('width')
    	viewBox += " " + selected.getAttribute('height')
    	svg.setAttribute("viewBox", viewBox);
        }
    }
    
    document.getElementById('rect-1').addEventListener("click", zoomOnElement);
    document.getElementById('rect-2').addEventListener("click", zoomOnElement);
    <svg xmlns="http://www.w3.org/2000/svg" width="300" height="200" viewBox="0 0 600 400" id="svg">
    
       <rect id="background" width="600" height="400" fill="#eee"/>
       <rect id="rect-1" x="100" y="50" width="50" height="300" fill="red"/>
       <rect id="rect-2" x="225" y="175" width="300" height="50" fill="blue"/>
       
    </svg>