How to extract position, rotation and scale from an SVG matrix

I have a simple problem: I want to extract the translation (tx, ty), rotation (r), and scale (sx, sy) values ​​from the transformation matrix applied to my svg element.

Use this example:

<g id="myElement" transform="matrix(0.93893241,0.34410162,-0.34410162,0.93893241,363.88475,-76.125919)" >... </g> 

If in javascript i do

 document.getElementById("myElement").getCTM() 

I can access the values ​​a, b, c, d, e, f. How can I get tx, ty, sx, sy and r from there? Thanks

+7
source share
1 answer

Inspired by this version of ActionScript: https://gist.github.com/fwextensions/2052247 , I wrote a JavaScript port:

  function deltaTransformPoint(matrix, point) { var dx = point.x * matrix.a + point.y * matrix.c + 0; var dy = point.x * matrix.b + point.y * matrix.d + 0; return { x: dx, y: dy }; } function decomposeMatrix(matrix) { // @see https://gist.github.com/2052247 // calculate delta transform point var px = deltaTransformPoint(matrix, { x: 0, y: 1 }); var py = deltaTransformPoint(matrix, { x: 1, y: 0 }); // calculate skew var skewX = ((180 / Math.PI) * Math.atan2(px.y, px.x) - 90); var skewY = ((180 / Math.PI) * Math.atan2(py.y, py.x)); return { translateX: matrix.e, translateY: matrix.f, scaleX: Math.sqrt(matrix.a * matrix.a + matrix.b * matrix.b), scaleY: Math.sqrt(matrix.c * matrix.c + matrix.d * matrix.d), skewX: skewX, skewY: skewY, rotation: skewX // rotation is the same as skew x }; } 

Usage: decomposeMatrix(document.getElementById('myElement').getCTM())

+16
source

All Articles