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:00100100Zoom X2:25255050Zoom X4:37.537.52525

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)=25Zoom 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><linkrel="stylesheet"href="https://codepen.io/basement/pen/oepKxY.css"></head><body><iframesrc="https://s.codepen.io/basement/debug/zdpVyV/PNAvYLZmJRQr"id="grid"
  ></iframe><divclass="wrp"><!-- SVG relevant code below--><svgxmlns="http://www.w3.org/2000/svg"viewBox="37.5 37.5 25 25"width="100"height="100"class="canvas"
    ><defs><styletype="text/css"> 

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

        </style></defs><circlecx="37.5"cy="50"r="25" /><circlecx="62.5"cy="50"r="25" /><circlecx="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;

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

functionzoomOut(){
    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?"