简体   繁体   中英

Center SVG viewbox X and Y based on content

Let's say I have the following SVG:

  <svg width="640" height="480" viewbox="0 0 640 480" style="border: 1px dotted black;"> <line x1="0" y1="0" x2="100" y2="0" stroke="black"></line> <line x1="100" y1="0" x2="100" y2="100" stroke="black"></line> <line x1="100" y1="100" x2="0" y2="100" stroke="black"></line> <line x1="0" y1="100" x2="0" y2="0" stroke="black"></line> </svg> 

This draws a square in the top left corner of the SVG.

If I want to move the viewbox so the square is centerd, I can change the viewbox X and Y like this:

 <svg width="640" height="480" viewbox="-270 -190 640 480" style="border: 1px dotted black;"> <line x1="0" y1="0" x2="100" y2="0" stroke="black"></line> <line x1="100" y1="0" x2="100" y2="100" stroke="black"></line> <line x1="100" y1="100" x2="0" y2="100" stroke="black"></line> <line x1="0" y1="100" x2="0" y2="0" stroke="black"></line> </svg> 

My question is, can the same result be achieved without changing the viewbox X and Y nor the lines Xs and Ys?

Yes. Use a transform (as @sean suggested).

 <svg width="640" height="480" viewbox="0 0 640 480" style="border: 1px dotted black;"> <g transform="translate(270, 190)"> <line x1="0" y1="0" x2="100" y2="0" stroke="black"></line> <line x1="100" y1="0" x2="100" y2="100" stroke="black"></line> <line x1="100" y1="100" x2="0" y2="100" stroke="black"></line> <line x1="0" y1="100" x2="0" y2="0" stroke="black"></line> </g> </svg> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM