如何在d3中创建多个正方形?

时间:2016-09-30 17:00:36

标签: javascript jquery loops d3.js svg

我有一个交互式页面,我需要使用d3在页面上显示多个方块,并带有以下计数:1,4,5,16,107,465和1745.我不想复制并且多次粘贴此SVG片段。

如何在d3中生成这些方块?

index.html

<svg width="50" height="50">
    <rect x="0" y="0" width="10" height="10" fill="#c62828">
</svg>

1 个答案:

答案 0 :(得分:2)

这是最短且“最干净”的d3代码,符合我对您的问题的理解。我已经评论过了,所以如果有些事情没有意义,请告诉我:

<!DOCTYPE html>
<html>

  <head>
    <script data-require="d3@4.0.0" data-semver="4.0.0" src="https://d3js.org/d3.v4.min.js"></script>
  </head>

  <body>
    
    <script>
    
    // number of rects
    var data = [1, 4, 5, 16, 107, 465, 1745];
         
    var squareDim = 10, // pixel dimensions of square
        width = 400,
        height = (squareDim * d3.max(data)) + squareDim; // based on the max of my squares, how tall am I going to be
        
    var svg = d3.select('body')
      .append('svg')
      .attr('width', width)
      .attr('height', height); // create my svg node
    
    var row = 0;
    svg.selectAll('rectGroup')
      .data(data)
      .enter()
      .append('g') // for each data point create a group
      .selectAll('rect')
      .data(function(d){
        return d3.range(d); // this creates an array of [1, 2, 3 ... N] where N is a datum in your rect data
      }) // this is a sub selection, it allows you to define a sub dataset
      .enter()
      .append('rect')
      .attr('width', squareDim)
      .attr('height', squareDim)
      .attr('x', function(d,i,j){
        return data.indexOf(j.length) * (squareDim + 2);
      }) // determine the x position
      .attr('y', function(d){
        return d * (squareDim + 2);  // and y
      })
      .style('fill', '#c62828');
      
    </script>
    
  </body>

</html>