在SVG中创建行

时间:2014-10-31 21:55:56

标签: javascript svg d3.js

在下面的代码中,我在彼此的顶部添加了三行,彼此间隔很小。但是,我想知道还有另一种方法可以使代码更加模块化吗?

我的意思是,不是为每个人复制和粘贴legend.append("line"),我想可能有更好的方法来制作一个而不是三个。

enter image description here

    var legendData = [{ color: "white", text: "MyData" }];
        var legends = svg.selectAll("g legends").data(legendData);
        var legendBox = legends.enter()
             .append("g")


       legendBox.append("line")
          .attr("x1", 200)
          .attr("x2", 215)
          .attr("y1", 24)
          .attr("y2", 24)
          .attr("stroke", "steelblue")
          .attr("stroke-width", "2")


        legendBox.append("line")
          .attr("x1", 200)
          .attr("x2", 215)
          .attr("y1", 12)
          .attr("y2", 12)
          .attr("stroke", "green")
          .attr("stroke-width", "2")


        legendBox.append("line")
          .attr("x1", 200)
          .attr("x2", 215)
          .attr("y1", 0)
          .attr("y2", 0)
          .attr("stroke", "red")
          .attr("stroke-width", "2")

2 个答案:

答案 0 :(得分:2)

如果连接了这些线,则可以使用折线或多边形。但是对于这种情况,没有其他方法(至少没有严重的方法),然后分别定义每一行。但是,您可以像这样生成它们:

colors = ["steelblue", "green", "red"];
for(i=0;i<3;i++)
{
   legendBox.append("line")
      .attr("x1", 200)
      .attr("x2", 215)
      .attr("y1", i*12)
      .attr("y2", i*12)
      .attr("stroke", colors[i])
      .attr("stroke-width", "2")
}

答案 1 :(得分:2)

D3方法是将坐标定义为数据,然后相应地选择和匹配:

var data = [{x1: 200, x2: 215, y1: 24, y2: 24, color: "steelblue"},
            {x1: 200, x2: 215, y1: 12, y2: 12, color: "green"},
            {x1: 200, x2: 215, y1: 0, y2: 0, color: "red"}];

legendBox.selectAll("line").data(data)
  .enter().append("line")
  .attr("x1", function(d) { return d.x1; })
  .attr("x2", function(d) { return d.x2; })
  .attr("y1", function(d) { return d.y1; })
  .attr("y2", function(d) { return d.y2; })
  .attr("stroke", function(d) { return d.color; })
  .attr("stroke-width", "2");