Search code examples
javascriptd3.jstag-cloud

Words go out of the borders in d3.js tag cloud


I want to create word tag cloud using d3 .. I found a good example here but the problem that the words go outside the borders especially in case of large fonts and this screenshot for the problem enter image description here

and here's my code

<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>

anyone know a solution for this?


Solution

  • Just change the following line in draw():

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

    to:

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

    Since your SVG's size is 700x700, you want the g transform to be in the middle of the SVG as the text elements are anchored in the middle.