Search code examples
d3.jssnap.svgweb-frontend

How to flatten a transformed svg path


I am trying to use the Snap.Svg javascript library to create a new path string in svg from a previously transformed path. The new path string must have the old transformations baked into it when it is created. The problem is I am not sure what exactly the correct approach is.I have looked at this thread Get the current matrix transformation of an SVG element but when I try to get the matrix to object to add to this method in snap.svg I get undefined. How can I get the transformation matrix object from the DOM node as shown in this example Apply transformation to result of previous transformation on SVG path. The relevant method in the snap library I think is http://snapsvg.io/docs/#Snap.path.map

My code:

   var result = d3.select(".line").node();
   console.log(result.transform.baseVal.consolidate().matrix);

The above returns null. How do I create/get the right transformation matrix object so I can use the Snap.path.map method?


Solution

  • Not sure if you are using d3 or Snap, so answer may depend. If Snap, you could look at getting the matrix from

    element.transform().localMatrix or 
    element.transform().globalMatrix 
    

    and then using that matrix use

    Snap.path.map( pathString, Matrix ) 
    

    from http://snapsvg.io/docs/#Snap.path.map to apply that transform

    If you need to get the transform string, you can get that from

    somepath.attr('d')