我正在通过修改来自:https://github.com/jasondavies/d3-cloud的代码来创建一个wordcloud。我可以通过修改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>发布于 2014-12-28 03:20:49
解决方案# 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,它是视图端口宽度。这是一个css3特性,它将根据视口调整文本大小。然而,您将需要适当地调整实际宽度和高度。
试着阅读本文: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 =“大字体”等那样做。
不要使用JS提供单词的宽度和高度,而是使用媒体查询断点将类分配给它们。
读:mediaquery.asp
我推荐解决方案2,因为我认为vw和vh并不是所有浏览器都支持的。http://caniuse.com/#feat=viewport-units。据报告,有一些问题与此有关。
发布于 2016-09-29 11:44:21
解决方案# 3:
要计算字体大小,您必须创建此比例:
var fontSizeScale = d3.scale.pow().exponent(5).domain([0,1]).range([ minFont, maxFont]);并在fontSize函数中调用它:
var maxSize = d3.max(that.data, function (d) {return d.size;});
.fontSize(function (d) {
return fontSizeScale(d.size/maxSize);
})若要将边界设置到屏幕/div,请执行以下操作:
在.on("end", drawCloud)函数中,调用此函数:
function zoomToFitBounds() {
var X0 = d3.min( words, function (d) {
return d.x - (d.width/2);
}),
X1 = d3.max( words, function (d) {
return d.x + (d.width/2);
});
var Y0 = d3.min( words, function (d) {
return d.y - (d.height/2);
}),
Y1 = d3.max( words, function (d) {
return d.y + (d.height/2);
});
var scaleX = (X1 - X0) / (width);
var scaleY = (Y1 - Y0) / (height);
var scale = 1 / Math.max(scaleX, scaleY);
var translateX = Math.abs(X0) * scale;
var translateY = Math.abs(Y0) * scale;
cloud.attr("transform", "translate(" +
translateX + "," + translateY + ")" +
" scale(" + scale + ")");
}https://stackoverflow.com/questions/27672989
复制相似问题