Vivek Kumar Vivek Kumar - 27 days ago 6
Javascript Question

Dynamically sized word-cloud using d3-cloud

I am creating a wordcloud by modifying code from : 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


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;[w, h])
.words(myArray) // from list.js
.fontSize(function(d) { return d.size; })
.on("end", drawCloud)

function drawCloud(words) {"body").append("svg")
.attr("width", w)
.attr("height", h)
.attr("transform", "translate(" + w/2 + "," + h/2 + ")")
.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; });


Solution # 1:

On line 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.

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:

Solution # 2:

On line 37:

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


   .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 :

I recommend solution 2 as i believe vw and vh is not supported by all the browsers. There are some issues reported related to that.