我正在尝试使https://www.jasondavies.com/wordcloud/上出现的词cloud出现在我的网站上。

我设法将示例中的一些代码(以及另一个SO答案)放在一起,并得出以下代码:

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; });
}


但这只会旋转单词“ 0”或“ 60度” https://imgur.com/a/fNyFH,中间没有任何旋转。如何使它与示例链接中的一样?

最佳答案

定义应用于单词的旋转方式的部分是:

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


在这里,您可以随机定义0或60的旋转角度。

the example you want to reproduce中,单词可以得到以下旋转:[-60,-30、0、30、60],可以使用以下方式获得:

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

07-26 09:29
查看更多