javascript - 获取 .attrs 方法内 d3 中文本节点的宽度

标签 javascript d3.js svg

我使用 d3 添加了一些文本节点,如下所示。

svg.selectAll('text.label')
    .data(studentTable, d => d.name)
    .enter()
    .append('text')
    .attrs({
      class: 'label',
      x: d => x(d.value),
      y: d => y(d.rank),
    })

现在在转换过程中我需要访问当前所选文本节点的宽度并根据宽度设置 x 位置。 (请参阅下面代码片段的注释)。

svg.selectAll('.label').data(studentTable, d => d.name)
        .transition()
        .duration(tickDuration)
        .ease(d3.easeLinear)
        .attrs({
          x: d => x(d.value), // Here i need to get the width of current text node to set x position
          y: d => y(d.rank)
        });

有什么方便的方法吗? 谢谢

最佳答案

获取文本长度的方法是getCompulatedTextLength(),您必须与节点一起使用。要获取箭头函数内的文本节点,请组合使用第三个和第二个参数。所以:

.attrs({
    x: (d, i, n) => n[i].getComputedTextLength() + whatever, 
    y: d => y(d.rank)
});

这是使用您的代码的演示,红线显示文本结尾:

const svg = d3.select("svg");
svg.selectAll('text.label')
  .data([{
    value: 100,
    rank: 50
  }])
  .enter()
  .append('text')
  .attrs({
    class: 'label',
    x: d => d.value,
    y: d => d.rank,
  })
  .text("Lorem ipsum dolor sit amet");
  
svg.append("line")
  .attr("x1", 100 + svg.select(".label").node().getComputedTextLength())
  .attr("x2", 100 + svg.select(".label").node().getComputedTextLength())
  .attr("y1", 0)
  .attr("y2", 100)
  .style("stroke", "red");

svg.selectAll('.label')
  .data([{
    value: 100,
    rank: 50
  }])
  .transition()
  .delay(1000)
  .duration(1000)
  .ease(d3.easeLinear)
  .attrs({
    x: (d, i, n) => d.value + n[i].getComputedTextLength(),
    y: d => d.rank
  });
<svg width="500" height="100"></svg>
<script src="https://d3js.org/d3.v5.min.js"></script>
<script src="https://d3js.org/d3-selection-multi.v1.min.js"></script>

关于javascript - 获取 .attrs 方法内 d3 中文本节点的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59377004/

相关文章:

javascript - SVG 路径渲染是否可以在 geometricPrecision 选项之外消除锯齿?

javascript - 在缩放和变换后获取 Snap.svg 中的新点

javascript - 如何使用 JavaScript 定位 SVG 路径的属性?

javascript:同一脚本的不同行为

javascript - 在新插件中使用 attr() 函数?

javascript - 使用 D3.js 只渲染 topojson map 的一部分

javascript - d3js 树布局中的对 Angular 线路径看起来不正确

javascript - svg 多边形点 - Javascript - 不起作用

javascript - Jade 模板引擎无法将 <p> 标记添加到 div 内部

javascript - 为什么所有对象的可观察属性值都是函数?