var width = 960,
height = 500;
var fill = d3.scale.category20();
var force = d3.layout.force()
.size([width, height])
.nodes([{}]) // initialize with a single node
.linkDistance(30)
.charge(-60)
.on("tick", tick);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.on("mousedown", mousedown);
svg.append("rect")
.attr("width", width)
.attr("height", height);
var nodes = force.nodes(),
links = force.links(),
node = svg.selectAll(".node"),
link = svg.selectAll(".link");
// var cursor = svg.append("circle")
// .attr("r", 30)
// .attr("transform", "translate(-100,-100)")
// .attr("class", "cursor");
restart();
function mousedown() {
var point = d3.mouse(this),
node = {
x: width / 2,
y: height / 2,
"number": Math.floor(Math.random() * 100)
},
n = nodes.push(node);
// add links to any nearby nodes
/* nodes.forEach(function(target) {
var x = target.x - node.x,
y = target.y - node.y;
if (Math.sqrt(x * x + y * y) < 30) {
links.push({source: node, target: target});
}
});
*/
restart();
}
function tick() {
link.attr("x1", function(d) {
return d.source.x;
})
.attr("y1", function(d) {
return d.source.y;
})
.attr("x2", function(d) {
return d.target.x;
})
.attr("y2", function(d) {
return d.target.y;
});
node.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
});
}
function restart() {
link = link.data(links);
link.enter().insert("line", ".node")
.attr("class", "link");
node = node.data(nodes);
// node.enter().insert("circle", ".cursor")
// .attr("class", "node")
// .attr("r", 5)
// .call(force.drag);
var nodeEnter = node.enter().insert("svg:g", ".cursor")
.attr("class", "node")
.call(force.drag);
nodeEnter.append("svg:circle")
.attr("r", 5)
nodeEnter.append("svg:text")
.attr("class", "textClass")
.attr("x", 14)
.attr("y", ".31em")
.text(function(d) {
return d.number;
});
force.start();
}
rect {
fill: none;
pointer-events: all;
}
.node {
fill: #000;
}
.cursor {
fill: none;
stroke: brown;
pointer-events: none;
}
.link {
stroke: #999;
}
.textClass {
stroke: #323232;
font-family: "Lucida Grande", "Droid Sans", Arial, Helvetica, sans-serif;
font-weight: normal;
stroke-width: .5;
font-size: 14px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>