2014-12-23 39 views
0

我想用d3創建單詞標籤雲..我發現了一個很好的例子here,但是單詞走出界限的問題尤其是在大字體和這種情況下截圖爲問題 enter image description here單詞在d3.js標籤雲中走出界限

,這裏是我的代碼

<script src="../lib/d3/d3.js"></script> 
<script src="../d3.layout.cloud.js"></script> 
<script> 
var fill = d3.scale.category20(); 

d3.layout.cloud().size([600, 600]) 
    .words([ 
     "Hello", "world", "normally", "you", "want", "more", "words", 
     "than", "this" 
    ].map(function(d) { 
     return { 
      text: d, 
      size: 10 + Math.random() * 90 
     }; 
    })) 
    .padding(5) 
    .rotate(function() { 
     return ~~(Math.random() * 2) * 90; 
    }) 
    .font("Impact") 
    .fontSize(function(d) { 
     return d.size; 
    }) 
    .on("end", draw) 
    .start(); 

function draw(words) { 
    d3.select("body").append("svg") 
     .attr("width", 700) 
     .attr("height", 700) 
     .append("g") 
     .attr("transform", "translate(150,150)") 
     .selectAll("text") 
     .data(words) 
     .enter().append("text") 
     .style("font-size", function(d) { 
      return d.size + "px"; 
     }) 
     .style("font-family", "Impact") 
     .style("fill", function(d, i) { 
      return fill(i); 
     }) 
     .attr("text-anchor", "middle") 
     .attr("transform", function(d) { 
      return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")"; 
     }) 
     .text(function(d) { 
      return d.text; 
     }); 
} 
</script> 

人知道一個解決方案?

回答

1

只需更改以下行draw()

 .attr("transform", "translate(150,150)") 

到:

 .attr("transform", "translate(350,350)") 

由於您的SVG的尺寸是700x700,你想要的摹變換是在SVG的中間作爲文本元素被錨定在中間。

+0

3天前我已經找到了這個解決方案,但是我忘了回答。感謝您的回答 :) –