Svg Matrix Expansion

In svg, we have an element.getCTM() method that returns SVGMatrix as:

 [ace][bdf][0 0 1] 

I want to calculate sx, sy and rotation angle from this matrix.

+7
source share
1 answer

There is a lot to read and learn about this topic. I will give a basic answer, but keep in mind that if you are trying to make a game or animation, this is NOT a way to do this.

a == sx and d == sy , so you will access them as follows:

 var r, ctm, sx, sy, rotation; r = document.querySelector('rect'); // access the first rect element ctm = r.getCTM(); sx = ctm.a; sy = ctm.d; 

Now for rotation a == cos(angle) and b == sin(angle) . Asin and acos cannot give you the full angle, but together they can. You want to use atan with tan = sin/cos , and for such a problem you really want to use atan2 :

 RAD2DEG = 180 / Math.PI; rotation = Math.atan2( ctm.b, ctm.a ) * RAD2DEG; 

If you study the inverse trigonometric functions and the unit circle, you will understand why this works.

Here W3C is an indispensable resource for SVG transformations: http://www.w3.org/TR/SVG/coords.html . Scroll down a bit and you can read a lot more about what I mentioned above.

UPDATE, an example of how to programmatically perform animations. Keep conversions stored separately, and when they are updated, overwrite / update the transform of the SVG element.

 var SVG, domElement, ... // setup SVG = document.querySelector( 'svg' ); domElement = SVG.querySelector( 'rect' ); transform = SVG.createSVGTransform(); matrix = SVG.createSVGMatrix(); position = SVG.createSVGPoint(); rotation = 0; scale = 1; // do every update, continuous use matrix.a = scale; matrix.d = scale; matrix.e = position.x; matrix.f = position.y; transform.setMatrix( matrix.rotate( rotation ) ); domElement.transform.baseVal.initialize( transform ); // clear then put 
+10
source

All Articles