How to get absolute coordinates of object inside a group?

后端 未结 5 1265
太阳男子
太阳男子 2020-12-07 15:08

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 de

5条回答
  •  天命终不由人
    2020-12-07 15:53

    @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

提交回复
热议问题