How to calculate SVG transform matrix from rotate/translate/scale values?

Vinay Bagale picture Vinay Bagale · Feb 28, 2013 · Viewed 21.5k times · Source

I have following details with me :

<g transform="translate(20, 50) scale(1, 1) rotate(-30 10 25)">

Need to change above line to:

<g transform="matrix(?,?,?,?,?,?)">

Can anyone help me to achieve this?

Answer

Peter Collingridge picture Peter Collingridge · Feb 28, 2013

Translate(tx, ty) can be written as the matrix:

1  0  tx
0  1  ty
0  0  1

Scale(sx, sy) can be written as the matrix:

sx  0  0
0  sy  0
0   0  1

Rotate(a) can be written as a matrix:

cos(a)  -sin(a)  0
sin(a)   cos(a)  0
0        0       1

Rotate(a, cx, cy) is the combination of a translation by (-cx, cy), a rotation of a degrees and a translation back to (cx, cy), which gives:

cos(a)  -sin(a)  -cx × cos(a) + cy × sin(a) + cx
sin(a)   cos(a)  -cx × sin(a) - cy × cos(a) + cy
0        0       1

If you just multiply this with the translation matrix you get:

cos(a)  -sin(a)  -cx × cos(a) + cy × sin(a) + cx + tx
sin(a)   cos(a)  -cx × sin(a) - cy × cos(a) + cy + ty
0        0       1

Which corresponds to the SVG transform matrix:

(cos(a), sin(a), -sin(a), cos(a), -cx × cos(a) + cy × sin(a) + cx + tx, -cx × sin(a) - cy × cos(a) + cy + ty).

In your case that is: matrix(0.866, -0.5 0.5 0.866 8.84 58.35).

If you include the scale (sx, sy) transform, the matrix is:

(sx × cos(a), sy × sin(a), -sx × sin(a), sy × cos(a), (-cx × cos(a) + cy × sin(a) + cx) × sx + tx, (-cx × sin(a) - cy × cos(a) + cy) × sy + ty)

Note that this assumes you are doing the transformations in the order you wrote them.