首页 > web前端 > css教程 > 正文

如何在 D3 中进行字符限制文本换行?

Linda Hamilton
发布: 2024-10-25 07:04:02
原创
736 人浏览过

How to Wrap Text in D3 with a Character Limit?

在 D3 中换行

要在 D3 中换行,您可以实现动态添加多个 的函数。 元素一定字符限制内的节点:

<code class="javascript">function wrap(text, width) {
  text.each(function () {
    var words = d3.select(this)
      .text()
      .split(/\s+/);

    words = words.reverse();

    var line = [];
    var lineNumber = 0;
    var lineHeight = 1.1; // ems
    var x = text.attr("x");
    var y = text.attr("y");
    var dy = 0; // parseFloat(text.attr("dy"));

    var tspan = text
      .text(null)
      .append("tspan")
      .attr("x", x)
      .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", x)
          .attr("y", y)
          .attr("dy", ++lineNumber * lineHeight + dy + "em")
          .text(word);
      }
    }
  });
}</code>
登录后复制

然后,您不必直接设置每个节点的文本,而是必须对其调用包装函数:

<code class="javascript">// Add entering nodes in the parent’s old position.
node.enter()
  .append("text")
  .attr("class", "node")
  .attr("x", function (d) { return d.parent.px; })
  .attr("y", function (d) { return d.parent.py; })
  .text("Foo is not a long word")
  .call(wrap, 30); // wrap the text in <= 30 pixels</code>
登录后复制

这将包装您的基于 范围内指定字符限制的文本节点,让它们像提供的示例一样自然流动。

以上是如何在 D3 中进行字符限制文本换行?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!