Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to translate an SVG group by a percentage of the viewport

Tags:

html

svg

I have an svg <rect> that is in a <g> (group) and I would like to scale it and then translate it by a percentage of the viewport. Most everything in svg allows the specification of units through a ridiculous number of options; e.g. px, em, %, ex, pt, pc, ... However it seems that the number specified in the translation is only pixels.

Thing is that if I have to go back and recalculate the pixel values for the translation, then my svg becomes resolution dependent. Then me, you and everyone would get sucked into a paradox. You can see why I'm a little concerned.

<svg>
  <g transform="scale(1, 1) translate(0, 0)">
    <rect x="45%" y="25%" height="50%" width="10%"/>
  </g>
</svg>

http://jsbin.com/ubeqot/1/edit

like image 855
QueueHammer Avatar asked Jun 13 '13 22:06

QueueHammer


People also ask

How to translate an SVG?

Stick the <g> element in an inner <svg> element and add x and y attributes with percentage values to the inner <svg> element to translate it. If you want the scale to apply first you would put the <svg> element inside the <g> instead.

What is a viewBox SVG?

The viewBox is an attribute of the SVG element in HTML. It is used to scale the SVG element that means we can set the coordinates as well as width and height. Syntax: viewBox = "min-x min-y width height" Attribute Values: min-x: It is used to set the horizontal axis.


1 Answers

Stick the <g> element in an inner <svg> element and add x and y attributes with percentage values to the inner <svg> element to translate it.

<svg>   <svg x="10%" y="20%">     <g transform="scale(1, 1)">       <rect x="45%" y="25%" height="50%" width="10%"/>     </g>   </svg> </svg> 

If you want the scale to apply first you would put the <svg> element inside the <g> instead.

like image 132
Robert Longson Avatar answered Sep 22 '22 01:09

Robert Longson