0

I am using D3, and trying to add a text label above an element that has undergone a rotational transform. My problem is how to position the text without actually rotating it too.

These are the original elements:

var circle = g.selectAll('.city')
 .data(data).enter()
 .append('circle')
 .attr('class', 'city')
 .attr('r', 10)
 .attr("cy", 0)
 .attr("cx", function(d) {
    return rdist(d.dist);
 }).attr("transform", function(d, i) {
    return "rotate(" + d.radial_pos + " 0 0)";
 });

And this is how I append the text, on mouseover:

circle.on("mouseover", function(d) {
  var cx = d3.select(this).attr('cx');
  var cy = d3.select(this).attr('cy');
  var label = d3.select(this.parentNode)
  .append('text')
  .text(function(d) {
    return d.name;
  }).attr('x', function() {
    return cx;
  }).attr('y', function() {
    return cy;
  }).attr("transform", function() {
    return "rotate(" + d.radial_pos + " 0 0)";
  });
});

This returns the labels in the right position, but the whole label is rotated, so the text is at an angle.

Is there some way that I can first transform the coordinates themselves, then set the text to those coordinates, so it remains the right way up? Alternatively, can I get the rendered position of the circle somehow?

4

1 に答える 1

1

この jsFiddle に示すように、要素のスプリアスtransform属性を削除すると問題が解決するようです:rotationtext

circle.on("mouseover", function(d) {
  var cx = d3.select(this).attr('cx');
  var cy = d3.select(this).attr('cy');
  var label = d3.select(this.parentNode)
  .append('text')
  .text(function(d) {
    return d.name;
  }).attr('x', function() {
    return cx;
  }).attr('y', function() {
    return cy;
  });
});

PS: これは次の質問に関連していると思います: D3.js: データが既にバインドされているときに要素を追加する方法は?

于 2013-01-23T17:14:06.053 に答える