chart = {
const GRID_SIZE = 25;
const GRID_COLS = 6;
const GRID_ROWS = Math.ceil(data.nodes.length / GRID_COLS);
let grid = {
cells : [],
init : function() {
this.cells = [];
for(var c = 0; c < GRID_COLS; c++) {
for(var r = 0; r < GRID_ROWS; r++) {
var cell;
cell = {
x : c * GRID_SIZE,
y : r * GRID_SIZE,
occupied : false
};
this.cells.push(cell);
};
};
},
sqdist : function(a, b) {
return Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2);
},
occupyNearest : function(p) {
var minDist = 1000000;
var d;
var candidate = null;
for(var i = 0; i < this.cells.length; i++) {
if(!this.cells[i].occupied && ( d = this.sqdist(p, this.cells[i])) < minDist) {
minDist = d;
candidate = this.cells[i];
}
}
if(candidate)
candidate.occupied = true;
return candidate;
}
}
grid.init();
console.log(grid.cells);
const nodes = data.nodes.map(d => Object.create(d));
const simulation = d3.forceSimulation(nodes)
.force("center", d3.forceCenter(width / 2, height / 2))
const svg = d3.select(DOM.svg(width, height));
const node = svg.append("g")
.attr("stroke", "#fff")
.attr("stroke-width", 1.5)
.selectAll("circle")
.data(nodes)
.join("circle")
.attr("r", 5)
.attr("fill", color)
.call(drag(simulation));
node.append("title")
.text(d => d.id);
simulation.on("tick", () => {
grid.init();
node
.each(function(d) {
let gridpoint = grid.occupyNearest(d);
if (gridpoint) {
d.x += (gridpoint.x - d.x) * .05;
d.y += (gridpoint.y - d.y) * .05;
}
})
.attr("cx", d => d.x)
.attr("cy", d => d.y);
});
invalidation.then(() => simulation.stop());
return svg.node();
}