简体   繁体   中英

Create rotations from -60 to 60 in d3.cloud

I am trying to get the word cloud as seen on https://www.jasondavies.com/wordcloud/ to be on my site.

I managed to put some code together from the examples (and another SO answer) and came to this code:

var fill = d3.scale.category20();

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

layout.start();

function draw(words) {
    d3.select(".wordcloud").append("svg")
        .attr("width", layout.size()[0])
        .attr("height", layout.size()[1])
        .append("g")
        .attr("transform", "translate(" + layout.size()[0] / 2 + "," + layout.size()[1] / 2 + ")")
        .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; });
}

But this only rotates the words only either 0 or either 60 degrees https://imgur.com/a/fNyFH , nothing in between. How do I make this to be as in the example link?

The part which defines the rotation to apply on words is:

.rotate(function() { return ~~(Math.random() * 2) * 60; })

Here you randomly define a rotation of either 0 or 60.

In the example you want to reproduce , words can get these rotations: [-60, -30, 0, 30, 60], which you can obtain using:

.rotate(function() { return ~~(Math.random() * 5) * 30 - 60; })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM