Vivek Kumar Vivek Kumar - 2 months ago 25
Javascript Question

Dynamically sized word-cloud using d3-cloud

I am creating a wordcloud by modifying code from : https://github.com/jasondavies/d3-cloud. I can change the size by modifying w & h but I want to scale the word cloud as the browser window changes. What would be the best method to achieve this for a js noob

Code also posted at 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>

Answer

Solution # 1:

On line 37:

.style("font-size", function(d) { return (d.size) + "px"; })

Replace

.style("font-size", function(d) { return (d.size/3) + "vh"; }) // "d.size/3" is an assumption use your appropriate relative width or height.

Instead of using px use vw which is view port width. It is a css3 feature that will resize the text according to the viewport. However, you will need to adjust the real width and height properly.

Try reading this article: http://css-tricks.com/viewport-sized-typography/

Solution # 2:

On line 37:

    .style("font-size", function(d) { return (d.size) + "px"; })

Use

   .attr("class", nameOfClass) // use class names here like 'big-font', 'med-font', 'small-font'

and in the CSS define the styles using media queries, the classes will be assigned depending upon the d.size in the condition so do it like if (d.size > 10) nameOfClass = "big-font" etc.

Instead of giving words width and height using JS, allocate classes to them using media queries breakpoints.

Read : http://www.w3schools.com/cssref/css3_pr_mediaquery.asp

I recommend solution 2 as i believe vw and vh is not supported by all the browsers. http://caniuse.com/#feat=viewport-units. There are some issues reported related to that.