olaf
olaf

Reputation: 65

How to calculate (SVG) X/Y coordinates out of translation and rotation (in JS/D3.js)?

The following function draws small circles in the middle of some arcs. I want to draw lines from these circles to other elements.

Thats why I need to get the cx/cy values of the circles (after they have been rotated).

var drawSmallCircles = function(arcs){
  var d=arcs;
  var arcRadius=d[0].outer;

  var svg = d3.select("svg").append("g")
      .attr("transform", "translate(" + width / 4 + "," + height / 2 + ")");

  var smallCircles = svg.selectAll("circle").data(d).enter().append("circle")
    .attr("fill","black")
    .attr("cx",0)
    .attr("cy",-arcRadius)
    .attr("r",4)
    .attr("transform", function(d) { 
      return "rotate(" + (((d.startAngle+d.endAngle)/2) * (180/Math.PI)) + ")";
    });
}

Best would be if someone could show me a function which gets the Arc-Radius and an Angle and returns (cx/cy). I would pre-calculate and store (cx/cy) in the "arcs-objects" and draw the circles and the lines out of those values.

The "translate" transformation is not really my problem.

Thank you!

Upvotes: 0

Views: 1415

Answers (2)

olaf
olaf

Reputation: 65

A friend of mine helped me with the following calculations:

    new_x= ( width/4 
        +Math.cos((d.startAngle+d.endAngle)/2 ) * (0            ) 
        -Math.sin((d.startAngle+d.endAngle)/2 ) * (-arcRadius)  );
    new_y= ( height/2 
        +Math.sin((d.startAngle+d.endAngle)/2 ) * (0           ) 
        +Math.cos((d.startAngle+d.endAngle)/2 ) * (-arcRadius) );

Upvotes: 1

ckersch
ckersch

Reputation: 7687

In this case, your first transform is applied to the g element, which contains a circle element that has a cy attribute and a rotation transform.

The first transform sets the origin of your group, the second rotates the circle around the origin at a distance of cy. Since your cy attribute is negative, the y-position relative to the origin will be given by -r*Math.cos(theta), while the x-position will be given by r*Math.sin(theta), where theta is the rotation angle in radians and r is the radial distance from the transformed origin to the center of the circle (arcRadius in your code).

Upvotes: 0

Related Questions