33

This may be a FAQ, so feel free to point me to another answer. The topic is difficult to search on.

If I want to use d3.js to get an attribute that's explicitly declared in an SVG object, or that I've explicitly put there using D3, I can easily get the value of the attribute using d3.select. For example, this prints 300:

...
<circle id="mycircle" r="10" cx="100" cy="200">
...
d3.select("#mycircle").attr("cx", 300);
console.log(d3.select("#mycircle").attr("cx"));

What if I don't explicit set the value of the attribute, but it is implicitly "set" from a <g> group? Or: How can I use code to find out where a <g> group is centered? I'd like some way of determining where in the absolute coordinate system of the <svg> object the things inside the <g> are. If I knew where the <g> was, how it's oriented in space, etc., I could figure out where points inside it are. How can I do that?

BigBadaboom remarks in a comment on an answer to this question that what is inherited is not a pair of coordinates, but a transform attribute. So I can select a <g> and get the value of the transform attribute:

console.log(d3.select("#mygroup").attr("transform"));

which prints, for example:

"rotate(-125.93)translate(0,-25)"

Do I have to parse that to find out where the <g> is situated in the absolute coordinate system?

3
  • 3
    You're looking for the getBBox() function. Don't have time to write a full answer now, but that's probably enough to get you on the right track.
    – AmeliaBR
    Sep 26, 2014 at 3:03
  • Thanks @AmeliaBR for passing on that information quickly! I didn't know about getBBox(). Wonderful tool. Doing some experimenting now. Looks like it only provides coordinates relative to SVG the <g> group, though. Rotations and translations in the transform attribute don't seem to affect the results of getBBox(). Maybe there's a way of using it that I haven't thought of yet.
    – Mars
    Sep 26, 2014 at 4:00
  • Note that at least for firefox getBBox() does not work on all elements
    – Skullquake
    Jun 27, 2018 at 14:04

6 Answers 6

52

Others here have already mentioned SVGLocatable.getBBox() which is useful for grabbing the bounding box of an element in terms of its own local coordinate system. Unfortunately, as you noticed, this doesn't take into account any of the transformations done on the element or on its parent elements.

There are a couple other functions available that will help you out a ton when dealing with those transforms.

SVGLocatable.getScreenCTM() gives you an SVGMatrix representing the transformations needed to convert from the viewport coordinates to the local coordinates of your element. This is great because it will take into account the transforms applied to the element it is called on, and any transforms applied to parent elements. Unfortunately, it also takes into account where exactly the element is on the screen, which means if you have content before your svg document, or even just some margins around it, the returned matrix will include that space as a translation.

Element.getBoundingClientRect() will allow you to account for that space. If you call this function on the SVG document itself, you can find out by how much the SVG is offset on the screen.

Then all you have to do is combine the two when you want to convert between coordinate systems. HERE is some good info on how an SVGMatrix works. The important thing to know for now is that an SVGMatrix is an object with six properties a, b, c, d, e, and f which represent a transformation as follows:

svg matrix equations

Lets say you have a variable svgDoc which is a reference to the svg document (not a d3 selection, but the element itself). Then you can create a function that will convert to the coordinate system of an svg element elem as follows.

function convertCoords(x,y) {

  var offset = svgDoc.getBoundingClientRect();

  var matrix = elem.getScreenCTM();

  return {
    x: (matrix.a * x) + (matrix.c * y) + matrix.e - offset.left,
    y: (matrix.b * x) + (matrix.d * y) + matrix.f - offset.top
  };
}

Then, say you wanted to put a dot in the middle of elem, you could do something like this:

var bbox = elem.getBBox(),
    middleX = bbox.x + (bbox.width / 2),
    middleY = bbox.y + (bbox.height / 2);

var absoluteCoords = convertCoords(middleX, middleY);

var dot = svg.append('circle')
  .attr('cx', absoluteCoords.x)
  .attr('cy', absoluteCoords.y)
  .attr('r', 5);

Of course, you'd probably want to generalize the convertCoords function so you can pass in the target element, but hopefully that'll get you off in the right direction. Good luck!

A better implementation would be a factory that generates a conversion function for any given element and svg document context:

function makeAbsoluteContext(element, svgDocument) {
  return function(x,y) {
    var offset = svgDocument.getBoundingClientRect();
    var matrix = element.getScreenCTM();
    return {
      x: (matrix.a * x) + (matrix.c * y) + matrix.e - offset.left,
      y: (matrix.b * x) + (matrix.d * y) + matrix.f - offset.top
    };
  };
}

This could be used as follows given the same elem and svgDoc as the naive example:

var bbox = elem.getBBox(),
    middleX = bbox.x + (bbox.width / 2),
    middleY = bbox.y + (bbox.height / 2);

// generate a conversion function
var convert = makeAbsoluteContext(elem, svgDoc);

// use it to calculate the absolute center of the element
var absoluteCenter = convert(middleX, middleY);

var dot = svg.append('circle')
  .attr('cx', absoluteCenter.x)
  .attr('cy', absoluteCenter.y)
  .attr('r', 5);
6
  • 1
    You reference a nonexistent variable elem in your convertCoords function
    – Andy Ray
    Sep 22, 2015 at 2:36
  • "Then you can create a function that will convert to the coordinate system of an svg element elem as follows."
    – jshanley
    Sep 22, 2015 at 18:19
  • 1
    You should edit your answer to fix the scoping problem of elem. You should pass it and do calculations inside the function. It's bad practice to declare and use a variable in the way you have.
    – Andy Ray
    Sep 23, 2015 at 17:35
  • Okay, I agree. The point of the original example was just to illustrate how to use the Element.getBoundingClientRect and SVGLocatable.getScreenCTM methods, not to create a general purpose function. However, since that may be helpful to have, I've updated the answer with a better, more general implementation.
    – jshanley
    Sep 24, 2015 at 0:54
  • 10
    This function is great for updating an element's position relative to another that's animating. But, when the SVG is scaled down, or its coordinate system isn't equal to the document's pixels, the calculations are off. Is there a way to account for a scaled-down coordinate system? May 23, 2016 at 6:19
10

@Jshanley's excellent answer is actually very easily implemented in raw JavaScript (or any framework) using SVGPoint's matrix transformation.

/**
* Get a new XY point in SVG-Space, where X and Y are relative to an existing element.  Useful for drawing lines between elements, for example

* X : the new X with relation to element, 5 would be '5' to the right of element's left boundary.  element.width would be the right edge.
* Y : the new Y coordinate, same principle applies
* svg: the parent SVG DOM element
* element: the SVG element which we are using as a base point.
*/
function getRelativeXY(x, y, svg, element){
  var p = svg.createSVGPoint();
  var ctm = element.getCTM();
  p.x = x;
  p.y = y;
  return p.matrixTransform(ctm);
}

See also: Rectangle coordinates after transform

In order to find the edges of your circle, for example:

var leftTangent = getRelativeXY(circle.cx-circle.r, circle.y, svg, circle);
var rightTangent = getRelativeXY(circle.cx+circle.r, circle.y, svg, circle);
var topTangent= getRelativeXY(circle.cx, circle.y-circle.r, svg, circle); 
var bottomTangent= getRelativeXY(circle.cx, circle.y+ circle.r, svg, circle);
var deadCenter= getRelativeXY(circle.cx, circle.y, svg, circle);

Admittedly not that interesting with a plain circle, but once the circle has been shifted or stretched it's a great tool for getting the coordinates.

W3's Spec

Microsoft's more easily understood tutorial

6
  • 1
    Your last line is incorrect. It should read return p.matrixTransform(ctm);
    – MSC
    Feb 1, 2017 at 10:19
  • I'm also running into trouble where the SVG's viewbox and width/height have different aspect ratios. Trying to fix it now...
    – MSC
    Mar 3, 2017 at 7:24
  • @MSC Ultimately if you set the aspect ratio, you can set either width or height, but not both. If you set both the height and width, you've redefined the aspect ratio to fit those dimensions. Mar 31, 2017 at 21:15
  • Would you be open to a tiny SVG consulting job by chance?
    – Crashalot
    Dec 24, 2018 at 9:26
  • @Crashalot I'd be open to consider it, though the comments section isn't a great place to have this discussion. Dec 26, 2018 at 16:04
7

D3 has a built in function to parse svg transforms: d3.transform

You could use it to get the translate array ([x, y]) of the transform, i.e.:

var transformText = d3.select("#mygroup").attr("transform");
var translate = d3.transform(transformText).translate;  //returns [0,-25]
0
7

To get the bounds of an SVG element, you have two options:

  1. getBBox() which works on all (graphical) SVG elements. It gets the bounding box of the element in local coordinate space. If the element has a transform attribute, it will affect the bbox, but if the parent element has a transform, it won't be reflected in the bbox returned.

    http://www.w3.org/TR/SVG/types.html#InterfaceSVGLocatable

  2. getBoundingClientRect() which is an HTML Element function, but also works for SVG elements. It returns the bounds of the element in screen space (after all transforms have been applied).

    https://developer.mozilla.org/en-US/docs/Web/API/Element.getBoundingClientRect

2

Nice demo here: https://codepen.io/netsi1964/pen/pWjwgP

point = point.matrixTransform(svg.getScreenCTM().inverse())
2

To me "absolute" could mean two things: screen pixels right and down from the SVG elements top-left corner, or userspace (i.e. viewBox coordinates). I was interested in the latter. For those wanting to take the last step of "transforming" the result of matrixTransform to absolute userspace coordinates, this worked for me:

function object_coords_to_userspace (x, y, object, svg) {
    // creates an SVGPoint with x,y coordinates inside an SVG element "object"
    // residing in parent svg, returns the location of the point in absolute
    // user space.

    // New point.
    point = svg.createSVGPoint();
    point.x = x;
    point.y = y;

    // New point location on screen where 0,0 is svg top left corner.
    coords_on_screen = point.matrixTransform(object.getCTM());

    // Convert screen coords to absolute userspace (i.e. respecting viewBox and svg element height and width).
    vphpx = svg.height.animVal.value;
    vpwpx = svg.height.animVal.value;



    // I thought I would need to implement this dumpster fire
    // (https://www.w3.org/TR/SVG/coords.html#ComputingAViewportsTransform) to
    // get the viewPort dimensions (as opposed to the viewBox).  If I use
    // preserveAspectRatio=none, the results are correct because the viewport
    // shows the viewBox exactly.  Otherwise in general the viewport shows the
    // viewBox /plus/ some in order to make up the space and preserve the
    // aspect ratio (because I'm using the default "xMidyMid meet" value for
    // preserveAspectRatio.  Was hoping the <svg> element would have a simple
    // way to get the transform from screen to userspace!?, however I have
    // managed to find that the svg element's getCTM().inverse() produces a way
    // to transform screen pixels x,y (relative to the viewports top-left
    // corner) into userspace coordinates.  Phew!
    point2 = svg.createSVGPoint();
    point2.x = 0;
    point2.y = 0;
    res = point2.matrixTransform(svg.getCTM().inverse())
    vpl = res.x;
    vpt = res.y;
    
    point3 = svg.createSVGPoint();
    point3.x = svg.clientWidth;
    point3.y = svg.clientHeight;
    res = point3.matrixTransform(svg.getCTM().inverse())
    
    vpw = res.x - vpl;
    vph = res.y - vpt;
    
    return {x: coords_on_screen.x/vpwpx*vpw + vpl, y: coords_on_screen.y/vphpx*vph + vpt}
1
  • getCTM return null on firefox: function getCTMAlt(svgElement){ return svgElement.getCTM() !== null ? svgElement.getCTM() document.createElementNS("http://www.w3.org/2000/svg", "svg").createSVGMatrix(); }
    – Spir
    Mar 9 at 13:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.