0

嗨,我想知道是否有人知道一种合适的方法来根据它所拥有的数据在圆圈的右侧或左侧对齐文本。

目前我有这个并且它有效:

//creating the circles & text together
 var node = svg.selectAll("a.node")
 .data(json)
 .enter().append("a")
 .attr("class", "node")
 ;

  //returning the shape & colors variable & linking it with the relevance in DB
node.append('path') 
    .attr("d", d3.svg.symbol().type(circle))
    .attr("transform", "translate(0,0)")

   ;
//returning the names from the db
node.append("text")
   .text(function(d) { return d.Name; })
   .style("font-size", "8px")
   .style("font", "Arial")
   .attr('x',  function (d) { 

          if (d.Field === "Canda"&& d.Name.length > 40) {return -180 }
            else if (d.Field === "Canda") {return 9}
          else {return 2} 

        ;})
   .attr('y', 2);

但是,由于我的 json 文本长度不同 - 当我说“-140”时,更短的文本甚至不接近圆圈。因此,无论长度是否变化,是否有一种动态方式使文本与圆的距离都相同?

编辑:刚刚添加了 .length .. 但这仍然意味着我需要做更多的 if 语句,因为文本的长度会有所不同。

http://jsfiddle.net/xwZjN/66/

4

1 回答 1

0

涉及文本锚的解决方案:

force.on("tick", function() {

   // edit to include text-anchor
   text.attr("text-anchor", function(d) { 
       if( d.Country ==="USA" ) { return "end" } 
       else { return "start" }
   } )
   // edit to change x starting point
   text.attr("x", function(d) {

           if (d.Country ==="USA") { 
                return d.x - 10;
           }
           else {  
               return d.x + 6; 
           } 
   })

   .attr("y", function(d) { return d.y + 4; });           

 node.attr("cx", function(d) { return d.x; })
     .attr("cy", function(d) { return d.y; });
});
于 2013-02-15T18:10:00.050 回答