简体   繁体   中英

Printing x number of elements per line with javascript and d3.js

I am trying to print x number of rectangles per line with d3.js

        var rectangle = svgContainer.selectAll("rect").data(data).enter().append("rect")
       .attr("x", function(d,i){ return i*5})
       .attr("y", function(d,i){ return i+1})
       .attr("width", 50)
       .attr("height", 50)

I know I need to modify the y attribute, but I feel like I'm blindly changing values until my rectangles print like

 [][][][][][]
 [][][][][][]
 [][][][][][]

instead of

      [[][[][[[][[][[][[]

or

      []
        []
          []
            []

Can I have some insight on how to come up with a formula to print accordingly?

Thank you

Something like this...

    var rectangle = svgContainer.selectAll("rect").data(data).enter().append("rect")
   .attr("x", function(d,i){ return (i%5) * 60})
   .attr("y", function(d,i){ return Math.floor(i / 5) * 60})
   .attr("width", 50)
   .attr("height", 50)

Your rects are height and width 50 so the 60 should ensure some gaps between them. 50 will result in no gaps and less than 50 overlapping rectangles.

% is the remainder operator we want the remainder after dividing by 5.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM