collision

collisions

by nancynancy

CSS

body,html{
  margin-top:30px;
  text-align: center;
	background-color:#669999;
}
#chart{
	background-color: #F5F2EB;
}

JavaScript

var w = 400;
var h = 300;
var nodes = d3.range(5).map(function(){
							return{
              		/* radius: Math.random() * 100 */
                  radius: 70
                  };
               }),
    root = nodes[0],
    color = d3.scale.category20b();
    
    console.log({nodes})

root.radius = 0;
root.fixed = true;

var force = d3.layout.force()
    .gravity(0.07)
    .charge(function(d, i) { return i ? 0 : -2000; })
    .nodes(nodes)
    .size([w, h]);

force.start();

var svg = d3.select("body").append("svg")
      .attr("id", "chart")
			.attr("width", w)
			.attr("height", h);
      
      
  var defs = svg.append('svg:defs');

  defs.append("svg:pattern")
    .attr("id", "seal")
    .attr("width", 350)
    .attr("height", 350)
    .attr("patternUnits", "userSpaceOnUse")
    .append("svg:image")
    .attr("xlink:href", 
    'https://img.freepik.com/free-vector/hand-drawn-floral-pattern-background_52683-16482.jpg?size=626&ext=jpg')
    .attr("width", 400)
    .attr("height", 400)
    .attr("x", -15)
    .attr("y", 20);


var chart = svg.append("g")
			.classed("display", true);

svg.selectAll("circle")
    .data(nodes.slice(1))
  .enter().append("circle")
    .attr("r", function(d) { return d.radius; })
    .style("fill", "url(#seal)")
    .attr("stroke", "red")
    /* .style("fill", function(d, i) { return color(i % 3); }); */

force.on("tick", function(e) {
  var q = d3.geom.quadtree(nodes),
      i = 0,
      n = nodes.length;

  while (++i < n) q.visit(collide(nodes[i]));

  svg.selectAll("circle")
      .attr("cx", function(d) { return d.x; })
      .attr("cy", function(d) { return d.y; });
});

svg.on("mousemove", function() {
  var p1 = d3.mouse(this);
  root.px = p1[0];
  root.py = p1[1];
  force.resume();
});

function collide(node) {
  var r = node.radius + 16,
      nx1 = node.x - r,
      nx2 = node.x + r,
      ny1 = node.y - r,
      ny2 = node.y + r;
  return function(quad, x1, y1, x2, y2) {
    if (quad.point && (quad.point !== node)) {
...