2

I am creating a mini SVG editor, I am doing it with pure JavaScript and I would like to generate a clean SVG, therefore, is there a formula, pattern, logic, algorithm, etc., to obtain the current command line values (aka drawing path) when applying a transform property to an svg path? Any documentation, article, tutorial, etc.? I have not been able to find results that explain something like this or that help the problem I have, mainly because I do not know how I could search for this topic or the keywords to which this topic refers. For example:

<svg width="111" height="95" viewBox="0 0 111 95" fill="none" xmlns="http://www.w3.org/2000/svg">
    <path id="my-path" transform="rotate(20)" d="M0.25 0L55 35L110.75 0V95L55 63L0.25 95V0Z" fill="#C4C4C4" />
</svg>

and in the JavaScript code have something like this:

const myPath = document.getElementById('my-path');
console.log(myPath.getRealValuesOfAttributeD());

// or

const getCurrentValuesOfAttributeD = (svgPathElement) => {
   // the formula, pattern, logic, algorithm, etc., goes here.
};


console.log(getCurrentValuesOfAttributeD(myPath));
Michael Mullany
  • 30,283
  • 6
  • 81
  • 105
Grizzly
  • 371
  • 2
  • 13
  • What do you mean by "current command line values"? Do you mean the current value of "d" - the drawing path? – Michael Mullany Sep 11 '21 at 15:54
  • Yes, in the MDN documentation it specifies "command line", apparently it is simply called attribute "d" jaja – Grizzly Sep 11 '21 at 16:02
  • 2
    myPath.getAttribute('d') but that won't change when a transform is applied. Writing code to do that would be long and involved and involve changing the commands themselves as and V or H commands would need to change to L. If that's what you want to to then you need to implement it and let us know if you get stuck on some particular aspect of it. Not sure why you'd do that though. – Robert Longson Sep 11 '21 at 16:16

1 Answers1

1

This is an introduction to transform matrix math for rotate, translate, etc. - which you'll need to do the calculations:

As Robert says - the Math is pretty complicated and there are hard to handle cases like the S command. You'd also need to convert every relative path command into an absolute path to get the math right.

If you're doing this because you're afraid of having a mess of nested transforms, then an easier way to do this might be to consolidate nested transforms by multiplying their matrix equivalents together - resulting in a single matrix transform for each element or group. It's still a bunch of math, but an order of magnitude easier than doing those path calculations.

Michael Mullany
  • 30,283
  • 6
  • 81
  • 105
  • It is something quite complex and confusing, I think that in the end I will settle for transformations jajaja. Thanks c: – Grizzly Sep 11 '21 at 19:06