Acanthus
Acanthus

Reputation: 43

Fixed font-size from an array - D3 Jason Davies Example

This Code below is an WordCloud example of Jason Davies. I want insert an array with fixed font-size and integrate it randomly.

e.g.:

fontSize = [20,35,50,60,83,90];

I want it fix, as above (not with range[x,x]) like this:

var fontSize = d3.scale.log().range([20, 90]); 

Has someone an idea how I can implement it.

Sorry, maybe it's a stupid question, am unfortunately still a beginner.

<script>
  var fill = d3.scale.category20();

  d3.layout.cloud().size([800, 800])
      .words([
        "Hello", "world", "normally", "you", "want", "more", "words",
        "than", "this"].map(function(d) {
        return {text: d, size: 10 + Math.random() * 90};
      }))
      .rotate(function() { return ~~(Math.random() * 2) * 90; })
      .font("Impact")
      .fontSize(function(d) { return d.size; })
      .on("end", draw)
      .start();

  function draw(words) {
    d3.select("body").append("svg")
        .attr("width", 800)
        .attr("height", 800)
      .append("g")
        .attr("transform", "translate(400,400)")
      .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; });
  }
</script>

Thanks!

Upvotes: 1

Views: 1035

Answers (1)

Lars Kotthoff
Lars Kotthoff

Reputation: 109242

All you should need to do to is to fix those sizes for the words you want instead of generating them randomly. You can append them to the array with random sizes:

var words = ["Hello", "world", "normally", "you", "want", "more", "words",
    "than", "this"].map(function(d) {
        return {text: d, size: 10 + Math.random() * 90};
    };
words.push({text: "foo", size: 20});
words.push(...);

The rest of the code shouldn't need any modifications at all. The code you've posted does not use any scales, so the font sizes that you generate and specify are the font sizes it will actually use.

Upvotes: 1

Related Questions