yAxis中的垂直对齐长文本用于水平条形图

时间:2017-11-10 11:39:18

标签: javascript d3.js

jsfiddle

我正在使用d3绘制水平条形图,但在y轴上垂直对齐文本会遇到问题。

以下是导致问题的代码:

.attr('transform', function(d) {
    var name = d;
    if (d.length > 20) {
      name = d.substring(0, 20) + '...';
    }
    var names = name.split(' ');
    return 'translate(0,' + (-names.length / 2) * 10 + ')';
  })
  .call(wrap, 50)

基本上,我为长文本添加省略号并调用wrap函数。但是,长文本没有垂直对齐。

任何帮助?

1 个答案:

答案 0 :(得分:1)

我重写了你的代码。查看diff here,工作示例 - https://jsfiddle.net/keqknbLb/1/

请注意我移动了数据绑定代码,在您的示例中,您在.call(yAxis)之前应用数据,因此创建了五个x轴。

与一些评论对齐的文字代码:

function wrap(text, width) {
      text.each(function() {
        var text = d3.select(this); // eslint-disable-line no-invalid-this
        var words = text.text()
            .split(/\s+/)
            .reverse();
        var word;
        var line = [];
        var lineHeight = 1.1;
        var lineNumber = 0;
        var y = 0;
        var x = 0;
        // var dy = 0;
        var tspan = text.text(null)
            .append('tspan')
            .attr('x', x)
            .attr('y', y)
            .text('1'); // set text for correct tspan height

        var tspanHeight =  tspan.node().getBBox().height; // get tspan height

        word = words.pop();

        while (word) {
          line.push(word);
          tspan.text(line.join(' '));

          if (tspan.node().getComputedTextLength() > width - x) {
            line.pop();
            tspan.text(line.join(' '));
            line = [word];
            lineNumber += 1;

            tspan = text.append('tspan')
                .attr('x', x)
                .attr('dy', lineHeight + 'em')
                .text(word);
          }
          word = words.pop();
        }

        var textHeight = text.node().getBBox().height; // get height of text element

        var yTransition = textHeight / 2 - tspanHeight / 2; // calculate y transiton value

        text.attr('transform', 'translate(-10,-'+ yTransition +')'); // apply transition
      });
    };