我正在通过修改以下代码来创建词云:https://github.com/jasondavies/d3-cloud .我可以通过修改 w & h 来改变大小,但我想随着浏览器窗口的变化来缩放词云。实现这一目标的最佳方法是什么?
代码也发布在 http://plnkr.co/edit/AZIi1gFuq1Vdt06VIETn?p=preview
<script>
myArray = [{"text":"First","size":15},{"text":"Not","size":29},{"text":"Bird","size":80}, {"text":"Hello","size":40},{"text":"Word","size":76},{"text":"Marketplaces","size":75}]
var fillColor = d3.scale.category20b();
var w = 400, // if you modify this also modify .append("g") .attr -- as half of this
h = 600;
d3.layout.cloud().size([w, h])
.words(myArray) // from list.js
.padding(5)
.rotate(0)
.font("Impact")
.fontSize(function(d) { return d.size; })
.on("end", drawCloud)
.start();
function drawCloud(words) {
d3.select("body").append("svg")
.attr("width", w)
.attr("height", h)
.append("g")
.attr("transform", "translate(" + w/2 + "," + h/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 fillColor(i); })
.attr("text-anchor", "middle")
.attr("transform", function(d,i) {
return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
}
)
.text(function(d) { return d.text; });
}
</script>
最佳答案
解决方案#1:
第 37 行:
.style("font-size", function(d) { return (d.size) + "px"; })
替换
.style("font-size", function(d) { return (d.size/3) + "vh"; }) // "d.size/3" is an assumption use your appropriate relative width or height.
不要使用 px
,而是使用 vw
,它是视口(viewport)宽度。这是一个 css3 功能,可以根据视口(viewport)调整文本大小。但是,您需要适当调整实际宽度和高度。
尝试阅读这篇文章:http://css-tricks.com/viewport-sized-typography/
解决方案#2:
第 37 行:
.style("font-size", function(d) { return (d.size) + "px"; })
使用
.attr("class", nameOfClass) // use class names here like 'big-font', 'med-font', 'small-font'
并且在 CSS 中使用媒体查询定义样式,类将根据条件中的 d.size 分配,所以这样做就像 if (d.size > 10) nameOfClass = "big-font"等
不是使用 JS 给单词宽度和高度,而是使用媒体查询断点为它们分配类。
阅读:http://www.w3schools.com/cssref/css3_pr_mediaquery.asp
我推荐解决方案 2,因为我认为并非所有浏览器都支持 vw
和 vh
。 http://caniuse.com/#feat=viewport-units .报告了一些与此相关的问题。
关于javascript - 使用 d3-cloud 动态调整词云大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27672989/