Skip to content Skip to sidebar Skip to footer

How To Keep Viewbox Centered When "zooming" In Svgs?

Often I use the viewBox attribute to 'zoom' a SVG element. Zoom is accomplished of course by using lower width and height values for the viewBox attribute - but the x and y values

Solution 1:

Your calculations are wrong. If the width and height of the viewBox get smaller, the x and y values need to get bigger.

Initial viewBox:  0 0 100 100
Zoom X2:          25 25 50 50
Zoom X4:          37.5 37.5 25 25

To get the x or y values, you need to subtract half the new width or height from the halfway point of the last (or original) viewBox.

Zoom X2:  centre - newWidth/2
          = (100/2) - (50/2) = 25
Zoom X4:  (100/2) - (25/2) = 37.5, or
          (25 + 50/2) - (25/2) = 37.5

Another waty to calculate it is to subtract the current width from the original width and divide by two.

Zoom X4:  (100 - 25) / 2 = 37.5

<head>
  <link rel="stylesheet" href="https://codepen.io/basement/pen/oepKxY.css">
</head>

<body> 
  <iframe src="https://s.codepen.io/basement/debug/zdpVyV/PNAvYLZmJRQr"
          id="grid"
  ></iframe>

  <div class="wrp">   
  
    <!-- SVG relevant code below-->
    <svg xmlns="http://www.w3.org/2000/svg"
         viewBox="37.5 37.5 25 25"
         width="100" height="100"
         class="canvas"
    > 
      <defs>   
        <style type="text/css"> 

          circle {
            fill: #0ff;
            fill-opacity: 0.25;
            stroke-width: 0.25;
            stroke: #0ee;
          }

        </style>       
      </defs>

      <circle cx="37.5" cy="50" r="25" />
      <circle cx="62.5" cy="50" r="25" />
      <circle cx="50" cy="71.65" r="25" />    
    </svg>
    
  </div>
</body>

Solution 2:

Since the code snippet expired and I had to give it some thought on how to implement it I thought I would spare others from doing it and post a working code snippet.

var svg = document.querySelector('svg');
var viewBox = svg.viewBox.baseVal;

function zoomIn(){
    viewBox.x = viewBox.x + viewBox.width / 4;
    viewBox.y = viewBox.y + viewBox.height / 4;
    viewBox.width = viewBox.width / 2;
    viewBox.height = viewBox.height / 2;
}

function zoomOut(){
    viewBox.x = viewBox.x - viewBox.width / 2;
    viewBox.y = viewBox.y - viewBox.height / 2;
    viewBox.width = viewBox.width * 2;
    viewBox.height = viewBox.height * 2;
}

If you implement a panning feature it will work with it too without any modifications.


Post a Comment for "How To Keep Viewbox Centered When "zooming" In Svgs?"