Not overcomplicating SVG transformations

Number Picture
2 min readMar 3, 2018

--

I make a lot of SVG charts. I’m trying to make more than 450 charts as part of my project Number Picture. I often ask myself why am I doing this — but that is a discussion for another day…

Quite often in charts you need to perform SVG transformations on elements. For example you might need to translate a shape from one position to another, or rotate an element. There are others as well: scale, matrix, skewX, skewY.

Sometimes, you might need to perform complex transformations on elements — ie more than one. And this is when it’s easy to make your life more difficult that it needs to be.

Consider the following example:

<svg width="100" height="100">
<rect
x="10"
y="10"
width="20"
height="10"
fill="black"
/>
</svg>

How would you rotate the rectangle around point [50, 50] 45 degrees AND at the same time around point [70, 80] 30 degrees?

<svg width="100" height="100">
<rect
x="10"
y="10"
width="20"
height="10"
fill="black"
transform="rotate(...?)"
/>
</svg>

Your first reaction might be to write a complex equation to calculate the centre of both rotations and the angle of rotation. However, this is not necessary. SVG already can perform these calculations for us without us having to perform the calculations ourselves.

All we need to do is apply multiple transformations to the same element like so:

<svg width="100" height="100">
<rect
x="10"
y="10"
width="20"
height="10"
fill="black"
transform="rotate(45, 50, 50) rotate(30, 70, 80)"
/>
</svg>

Or another approach is to use the SVG g tag. Each g tag has one transform and this might be easier to read for some.

<svg width="100" height="100">
<g transform="rotate(45, 50, 50)">
<g transform="rotate(30, 70, 80)">
<rect
x="10"
y="10"width="20"
height="10"
fill="black"
/>
</g>
</g>
</svg>

I hope you find this useful. Happy coding.

--

--