How to extract position, rotation and scale from matrix SVG
javascript, matrix, svg
Solution
Inspired by this ActionScript version: 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())`
Problem
I have a simple problem: I want to extract translation (tx, ty), rotation (r) and scale (sx, sy) values form a transform matrix applied to my svg element. Let's 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 to a, b, c, d, e, f values. How can I get tx, ty, sx, sy and r from there? Thanks