首页 > 解决方案 > 使用 d3.js 向 svg 添加注释(文本 + 行)的功能?

问题描述

// legend description for fire colors
legendContText = wrapLabel("Color indicates time to containment (darker = longer) ranging from 8 to 114 days.  This one took 113 days.", 160);
const legendCont = legendOverlay.append("g")
  .attr("class","legend cont");
const legendContSpans = legendCont.append("text")
  .attr("y", yScale(70));
legendContText.forEach(function(string) {
  legendContSpans.append('svg:tspan')
  .text(string)
  .attr("font-size",yScale(0.28).toString()+"rem")
  .attr('x', yScale(-150))
  .attr('dy', yScale(5))
});
legendCont.append("line")
  .attr("class","legend cont")
  .attr("x1", yScale(-150))
  .attr("y1", yScale(57))
  .attr("x2", yScale(-140))
  .attr("y2", yScale(70));

所以我在 d3 中创建了一个可视化,并在一个大 svg 中添加了几个注释——每一个都由几行文本(一个文本对象有几个 tspan)和一行组成。上面显示的是一个这样的注释的代码。

我的代码工作正常(在http://heidistockton.com/fireandice/查看结果)-我的问题是它太重复了,绝对不是最佳实践(我喜欢其中的 10-15 个,它们包括近 40 个% 我的代码按行数)。有人可以帮我确定一种方法来创建一个添加这样一个注释的函数吗? 

我希望这样一个函数的输入是:

  1. 一个字符串
  2. 文本换行的宽度
  3. 注释的类名(用于更简洁的 html)
  4. 文本框的 x/y 坐标,以及
  5. 线的两组 x/y 坐标

“wrapLabel”函数只接受一个字符串并根据长度将其分成更小的块(来自 Carys Mills 的代码)。我希望将 wrapLabel 函数嵌套在注释函数中,或者只包含 wrapLabel 函数的输出作为注释函数的输入。

我的项目的完整代码可以在这里找到:https ://github.com/heidi8297/heidi8297.github.io/blob/main/fireandice/main.js

标签: javascriptd3.js

解决方案


推荐阅读