interactivethings / d3-grid

D3 grid layout
BSD 3-Clause "New" or "Revised" License
77 stars 10 forks source link

Help me: I need your equal distribution algorithm but don't understand your code #10

Closed Naragorn closed 6 years ago

Naragorn commented 6 years ago

I exactly need your algorithm that places rectangles in a grid fashion for my application. I suspect it is in _function distributeEqually(nodes)
However I don't understand your code yet and have no experience with d3.

Can you give me any logic or semantic on how the algorithm works that places rectangles like that?

jstcki commented 6 years ago

Hi!

The two main parts should be this:

https://github.com/interactivethings/d3-grid/blob/9c31fd86769647fcce0eda49ca2b17de46cc74e0/d3-grid.js#L33-L34

… which calculates the number of columns and rows, so that they're roughly equal

and

https://github.com/interactivethings/d3-grid/blob/9c31fd86769647fcce0eda49ca2b17de46cc74e0/d3-grid.js#L56-L58

… where for each node (i.e. point on the grid) its col and row are calculated.

If you need more details, please let me know!

Naragorn commented 6 years ago

For

… where for each node (i.e. point on the grid) its col and row are calculated.

Is this the same for the rectangles? I only need the rectangles, and not the points

jstcki commented 6 years ago

What and how you draw at each point is up to you. This calculation only gives you the coordinates within the grid. For example:

const nodes = [{}, {}, {}, {}];
const n = nodes.length; // 4 in this case

// Figure out how many columns and rows we need
const cols = Math.ceil(Math.sqrt(nodes.length)); // => 2
const rows = Math.ceil(n / cols); // => 2

// Assign col/row to each node
nodes.forEach((node, i) => {
  node.col = i % cols;
  node.row = Math.floor(i / cols);
})

// Nodes now should be
// [{col: 0, row: 0}, {col: 1, row: 0}, {col: 0, row: 1}, {col: 1, row: 1}]
Naragorn commented 6 years ago

Perfect I just finished my task thanks to you!

Many thanks and kind regards!