Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get absolute coordinates of SVG path with Javascript

Tags:

javascript

svg

I am creating a program which converts a SVG file to my own format. I have created a web based application to do this. I use the default DOM parsing functionality of web browsers to iterate over the SVG contents.

With Javascript I can get a SVG path element using:

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

I can get the path segments using:

var pathSegments = path.pathSegList

However these path segments are relative to whatever parent SVG element is defined. Transforms are not included in the path segment list.

Is there a way to get the absolute coordinates of this path as they are ultimately used when drawn on the screen?

Example: say I got 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>

What I want is to retrieve is the coordinates of the path with the transforms of the two g elements applied. In this case the coordinates of the path should be:

[150,150], [160, 150], [160, 160]
like image 749
Mathyn Avatar asked Mar 04 '15 13:03

Mathyn


People also ask

Can we get an SVG document using Javascript?

Introduction. Like HTML, SVGs are represented using the Document Object Model (DOM) and so can be manipulated with Javascript relatively easily, especially if you are familiar with using JS with HTML.

What is path element SVG?

The <path> element is the most powerful element in the SVG library of basic shapes. It can be used to create lines, curves, arcs, and more. Paths create complex shapes by combining multiple straight lines or curved lines. Complex shapes composed only of straight lines can be created as <polyline> s.

Can I add class to SVG path?

Just the same as you would add a class to an html element, by adding a class attribute. Though to be able to target that with css the svg code must be inserted into the document in-line, it can't be referenced by an <img> tag for example.


1 Answers

You want is to do something like this to each path segment coordinate...

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>

If you're using Chrome and you find that there's no getTransformToElement function any more then this polyfill will restore that missing method.

like image 160
Robert Longson Avatar answered Sep 21 '22 05:09

Robert Longson