How to get current values from attribute "d" of SVG path when transform property is applied (pure JavaScript)?

783 views Asked by At

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));
1

There are 1 answers

1
Michael Mullany On

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.