force layout

HTML

<script src="https://d3js.org/d3.v3.min.js"></script>
<div id="container"/>

CSS

circle.node {
    stroke: #444;
    r: 5;
}
svg {
    background-color: #fefefe;
    border: 1px solid #ccc;
}

JavaScript

// Basic control variables
var numNodes = 4;
var counter = 1;
var height = 600;
var width = 600;
var color = d3.scale.category10();
var colorScale = d3.scale.linear().domain([0,width]).range([0,10]);

var nodes = [];
for(var i=0; i<numNodes; i++){
var fixed = false;
if(i==0) fixed = true;
    nodes.push({
        cx: Math.floor(Math.random()*width),
        amount: Math.floor(Math.random()*height),
        key: counter++,
        fixed : fixed
    });
}

var force = d3.layout.force()
    .nodes(nodes)
    .charge(function(d){ return d.amount * -.2; })
    .size([width, height])
    .on("tick", function(e){ 
            node.attr("cx", function(d) { return d.x + (d.x - d.cx); });
            node.attr("cy", function(d) { return d.y; });
        })
    .start();
    
// Create the initial structure of the game board (using SVG rectangles)
var svg = d3.select("#container").append("svg")
    .attr("height", height)
    .attr("width", width);

var node = svg.selectAll(".node")
    .data(nodes)
    .enter().append("circle")
        .attr("class", "node")
        .attr("cx", function(d) { return d.x; })
        .attr("cy", function(d) { return d.y; })
        .attr("r", function(d) { return d.amount * 0.05; })
        .attr("fill", function(d) { return color(Math.floor(colorScale(d.cx))); })
        .call(force.drag);