Bubbles

by nancynancy

HTML

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

JavaScript

// As always, thanks to Nadieh Bremer for the inspiration and code
// to tinker with and learn from!
// http://www.visualcinnamon.com/
////////////////////////////////////////////////////////////
///////// Set up and initiate svg containers ///////////////
var margin = {top: 20, right: 20, bottom: 30, left: 20};        
var width = 330 - margin.left - margin.right;
var height = 330 - margin.top + margin.bottom;

//SVG container
var svg = d3.select('#hexagon')
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");

////////////////////////////////////////////////////////////
/////////////////////// Calculate hexagon variables ////////
var SQRT3 = Math.sqrt(3),
    hexRadius = Math.min(width, height)/2,
    hexWidth = SQRT3 * hexRadius,
    hexHeight = 2 * hexRadius;

//Each vertex is relative to the previous, starting at the origin of the svg.
var hexagonPoly = [[0,-1],
                   [SQRT3/2,0.5],
                   [0,1],
                   [-SQRT3/2,0.5],
                   [-SQRT3/2,-0.5],
                   [0,-1],
                   [SQRT3/2,-0.5]];

var hexagonPath = "m" + hexagonPoly.map(function(p){ return [p[0]*hexRadius,
		p[1]*hexRadius].join(','); }).join('l') + "z";

///////////////////////////////////////////////////////////////////////////
////////////////////// Place circles inside hexagon ///////////////////////
//Create a clip path that is the same as the top hexagon
svg.append("defs").append("clipPath")
  .attr("id", "clip")
  .append("path")
  .attr("d", "M" + (width/2) + "," + (height/2) + hexagonPath);

//First append a group for the clip path, then a new group that can be transformed
var circleWrapperOuter = svg.append("g")
.attr("clip-path", "url(#clip)")
.style("clip-path", "url(#clip)"); //make it work in safari

var circleWrapperInner =...