Search code examples
javascriptsvgmatrixtransformation

Get the current matrix transformation of an SVG element


I know a very easy way to get the current matrix transformation of any SVG element:

// 't' is a string
var t = window.getComputedStyle(nativeElement, null).transform
console.log(t);

The problem is that the previous method returns numbers with no more than six decimals. For example, the previous code may return:

matrix(0.965926, 0.258819, -0.258819, 0.965926, 0, 0)

Is there a way to get the matrix transformation of any SVG element more accurately?


Solution

  • To get the current transform attribute as an SVGMatrix object, you can use:

    element.transform.baseVal.consolidate().matrix
    

    var myrect = document.getElementById("myrect");
    
    console.log(myrect.transform.baseVal.consolidate().matrix);
    <svg>
      <rect id="myrect" width="10" height="10" transform="scale(2) rotate(45)"/>
    </svg>