Get absolute coordinates of an SVG path using Javascript

I am creating a program that converts an SVG file to my own format. To do this, I created a web application. I use the default DOM parsing function for web browsers to iterate over SVG content.

With Javascript, I can get an SVG path element using:

var path = document.getElementById("path3388");

I can get path segments using:

var pathSegments = path.pathSegList

However, these path segments refer to any parent SVG element. Transformations are not included in the list of path segments.

Is there any way to get the absolute coordinates of this path, since they are ultimately used when drawing on the screen?

Example: let's say I have the following SVG snippet:

<g transform="translate(100, 100)">
    <g transform="translate(50, 50)">
        <path d="M 0,0 10,0 10,10"></path>
    </g>
</g>

I want to get the coordinates of a path with transformations of two g elements. In this case, the coordinates of the path should be:

[150,150], [160, 150], [160, 160]
+4
1

- ...

var root = document.getElementById("root");
var path = document.getElementById("path");
var point = root.createSVGPoint();
point.x = 0;  // replace this with the x co-ordinate of the path segment
point.y = 0;  // replace this with the y co-ordinate of the path segment
var matrix = path.getTransformToElement(root);
var position = point.matrixTransform(matrix);

alert(position.x + ", " + position.y);
<svg id="root">
  <g transform="translate(100, 100)">
    <g transform="translate(50, 50)">
        <path id="path" d="M 0,0 10,0 10,10"></path>
    </g>
</g>
</svg>
Hide result
+5

All Articles