Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 846
Vinay Bagale Avatar asked Feb 28 '13 11:02

Vinay Bagale


People also ask

What is transform matrix in SVG?

The transform attribute defines a list of transform definitions that are applied to an element and the element's children. Note: As of SVG2, transform is a presentation attribute, meaning it can be used as a CSS property.

What is CTM SVG?

For each given element, the accumulation of all transformations that have been defined on the given element and all of its ancestors up to and including the element that established the current viewport (usually, the 'svg' element which is the most immediate ancestor to the given element) is called the current ...

How do I rotate a path in SVG?

Just use the element type selector and add the transform: rotate(180deg) property to it like in the below snippet. Show activity on this post. Inline you would do it like this: x-axis flip : transform="scale(-1 1)"


2 Answers

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.

like image 130
Peter Collingridge Avatar answered Sep 28 '22 12:09

Peter Collingridge


First get the g element using document.getElementById if it has an id attribute or some other appropriate method, then call consolidate e.g.

var g = document.getElementById("<whatever the id is>"); g.transform.baseVal.consolidate(); 
like image 44
Robert Longson Avatar answered Sep 28 '22 10:09

Robert Longson