我正在尝试将在 https://www.jasondavies.com/wordcloud/ 上看到的词云放在我的网站上。
我设法将示例中的一些代码(和另一个 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; })
关于javascript - 在 d3.cloud 中创建从 -60 到 60 的旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49285933/