使用D3.js从单个数据点生成多个DOM元素

时间:2016-03-28 20:49:22

标签: javascript d3.js

假设我有这样的数据:

[{from: 3, to: 5}, {from: 1, to: 2}]

我想生成以下SVG:

<svg width="100" height="100">
  <g transform="translate(0,0)">
    <rect x="0" width="5" height="5"></rect>
    <rect x="10" width="5" height="5"></rect>
    <rect x="20" width="5" height="5"></rect>
  </g>
  <g transform="translate(0,30)">
    <rect x="0" width="5" height="5"></rect>
    <rect x="10" width="5" height="5"></rect>
  </g>
</svg>

基本上,对于每个数据点,我必须生成to - from + 1矩形。这就是我的开始:

var width = 100;
var x = d3.scale.ordinal()
  .domain(d3.range(10))
  .rangeRoundBands([0, width]);

var svg = d3.select('svg').append('svg')
  .attr('width', width)
  .attr('height', 100);
var row = svg.selectAll('g')
  .data(data)
  .enter().append('g')
  .attr('transform', function(d, i) { return 'translate(0,' + i * 30 + ')';});

现在,如何使用链式语法为每个数据点生成多个rects?

我知道我可以这样做:

var rects = row.selectAll('rect')
  .data(function(d) { return d3.range(d.to - d.from + 1);})

但我想避免创建无用的数组。

1 个答案:

答案 0 :(得分:1)

您可以在append()函数中迭代并在那里动态创建您的rects:

&#13;
&#13;
var data = [{from: 3, to: 5}, {from: 1, to: 2}, {from: 4, to: 9}];

var width = 100;

var x = d3.scale.ordinal()
  .domain(d3.range(10))
  .rangeRoundBands([0, width]);

var svg = d3.select('div').append('svg')
  .attr('width', width)
  .attr('height', 100);

var row = svg.selectAll('g')
  .data(data)
  .enter().append(function(d) {
    var rects = document.createElementNS('http://www.w3.org/2000/svg', 'g');
    for (var i = d.from; i <= d.to; i++) {
      var rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
      rect.setAttribute('width', 5);
      rect.setAttribute('height', 5);
      rect.setAttribute('x', (i - d.from) * 10);
      rects.appendChild(rect);
    }
    return rects;
  })
  .attr('transform', function(d, i) {
    return 'translate(0,' + i * 30 + ')';
  });
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div></div>
&#13;
&#13;
&#13;