Frage

I'm trying to transform a word cloud to a word list. I've managed to do but hit a problem on animating text. Because word cloud uses text-anchor: middle for text positioning, when I switch to list layout which uses text-anchor: start, words spikes a bit as animation starts. See fiddle and related code below:

jsFiddle

text.transition()
    .duration(1000)
    .attr("text-anchor", opts.textAnchor)
    .attr("transform", function(d) {
         return "translate(" + [d.x, d.y] + ")";
     })
     .style("font-size", function(d) {
          return d.size + "px";
     })

I think, I should calculate each text position manually and create my own centered text instead of text-anchor: middle. But I'm not sure how to do it.

Any help would be appreciated

War es hilfreich?

Lösung

The best way is indeed to center the text yourself instead of using and animating text-anchor. This is relatively easy, you just have to determine the width of the text and offset it by half that length to center:

.attr("dx", function() {
  if(opts.textAnchor == "start") {
    return 0;
  } else if(opts.textAnchor == "middle") {
    return -this.getBBox().width/2 + "px";
  }
})

Complete demo here.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top