0

I am trying to create thin rectangle charts and I need a method that could take the text and wrap it properly.

The goal is to create something like this.

enter image description here

http://jsfiddle.net/0ht35rpb/167/

d3.js how to apply text wrapping declaratively Lars had come up with a solution - and I've tried to implement it here - but I couldn't get it to work.

http://jsfiddle.net/0ht35rpb/168/

const axisLabel = chart
  .append("g")
  .append("text")
  .attr('x', function(d) {
    return path.centroid(d)[0];
  })
  .attr('y', function(d) {
    return path.centroid(d)[1] + 4;
  })
  .each(function(d) {
      var arr = d.properties.eventname.split(" ");
      if (arr != undefined) {
        for (var i = 0; i < arr.length; i++) {
          d3.select(this).append("tspan")
            .text(function() {
                return arr[i];
              })
              .attr("y", path.centroid(d)[1] + i * 8 + 8)
              .attr("x", path.centroid(d)[0])
              .attr("text-anchor", "middle");
            }
        }
      });

there is this method here with tspans and this nearly works - but the text is not centered?

http://jsfiddle.net/0ht35rpb/169/

function wrap(text, width) {
  text.each(function() {
    var text = d3.select(this),
        words = text.text().split(/\s+/).reverse(),
        word,
        line = [],
        lineNumber = 0,
        lineHeight = 1.1, // ems
        y = text.attr("y"),
        dy = parseFloat(text.attr("dy")),
        tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
    while (word = words.pop()) {
      line.push(word);
      tspan.text(line.join(" "));
      if (tspan.node().getComputedTextLength() > width) {
        line.pop();
        tspan.text(line.join(" "));
        line = [word];
        tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
      }
    }
  });
}

1 Answers1

0

You don't have any path in your code and, therefore, no centroid.

Thus, it should be:

.attr('x', function(d) {
    return config.width / 2;
})
.attr('y', function(d) {
    return config.height;
})

Here is your updated fiddle: http://jsfiddle.net/vumbvs9s/

Regarding your second fiddle, just change Bostock's function to get the current x position:

var x = text.attr("x");

Here is the updated fiddle: http://jsfiddle.net/a0s8h3wg/

Gerardo Furtado
  • 100,839
  • 9
  • 121
  • 171