【问题标题】:Wrapping text labels环绕文本标签
【发布时间】:2015-04-17 08:46:53
【问题描述】:

目前正在尝试在我的图表上包装一些文本标签。我正在关注 Mike Bostock 的示例 here。当我尝试实现他的示例时,它适用于我的 y 轴,但我需要它在我的 x 轴上工作,我不确定它为什么不工作。

 chart2.append("g")
        .attr("class", "y axis")
        .call(yAxis)
        .append("text")
        .attr("transform", "rotate(-90)")
        .attr("y", 6)
        .attr("dy", ".71em")
        .style("text-anchor", "end")
        .text("Potential Years Lost")
        .call(wrap, x0.rangeBand());


  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);
      }
    }
  });
}

function type(d) {
  d.value = +d.value;
  return d;
}

这是我的小提琴:http://jsfiddle.net/flyingburrito/0xq0qc42/1/

【问题讨论】:

    标签: d3.js


    【解决方案1】:

    小改动,您实际上并没有在 x 轴刻度文本上调用 wrap(您只是为 y 轴标签调用它)。

    您需要将最后两行添加到附加 x 轴的块中

    //draw the bars
    chart2.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis)
        .selectAll(".tick text")
        .call(wrap, x0.rangeBand());
    

    在这里工作:http://jsfiddle.net/henbox/v5fj0263/

    【讨论】:

      【解决方案2】:

      或者您可以使用带有 html 的外部对象:

      1. 添加外部对象,然后使用 xhtml 内容。

      var fo = nodes.append("foreignObject")
        .style("pointer-events", "none")
        .attr("id", "fo")
        .attr("width", function(d) {
          return Math.max(32, this.getComputedTextLength() + 12);
        });
      
      fo.append("xhtml:body")
        .style("text-align", "center")
        .append("div")
        .attr("class", "fotext")
        .style("margin", "0px auto")
        .style("font", "14px 'Helvetica Neue'")
        .style("overflow", "auto")
        .html(function(d) {
          return d.name
        });
      
      fo.attr("transform", function(d) {
        return translateInMiddle(this)
      });
      
      function translateInMiddle(object) {
        bbox = object.getBBox();
        return "translate(" + [-bbox.width / 2, -bbox.height / 8] + ")";
      }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-08-18
        • 2021-04-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-03
        • 1970-01-01
        • 2013-07-15
        相关资源
        最近更新 更多