Search code examples
svg.js

Can I apply the transform to a path so the transform itself is no longer needed?


Is it possible to "apply" a transform to a node using SVG.js? I'm not asking about how to add a transform attribute to a node, but recalculate that node's coordinates so the transform itself is no longer needed - it is now baked into the coordinates of the node itself. For example, let's say I have a polygon (really, a rectangle) of (0,0) (100,0) (100, 10) (0, 10) and I have a scale transform applied to it of 2x. I'd like to flatten this node so it does not have the transform anymore, but is now (0,0) (200,0) (200, 20) (0, 20)

Thank you!


Solution

  • Yes and no. If you have a path and you use the arc command in your path, not all transformations can be applied 1to1 so that the path looks the same.

    If you are OK with this limitation, you can loop through all commands of the path array and apply the transform to every point individually.

    Untested pseudocode:

    const pathArray = path.array()
    
    for (const cmd in pathArray) {
      // this will not work for h, v and z commands 
      const x = cmd.pop()
      const y = cmd.pop()
      const p = new SVG.Point(x,y).transform(path.transform())
      cmd.push(p.x, p.y)
    }
    
    path.untransform().plot(pathArray)
    

    For polygons, you can do the same but with the points array instead. Rectangles can be converted to polygons first