Skip to content

Instantly share code, notes, and snippets.

@pbogden
Last active January 4, 2017 14:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pbogden/8621067 to your computer and use it in GitHub Desktop.
Save pbogden/8621067 to your computer and use it in GitHub Desktop.
Responsive circles
<!DOCTYPE html>
<meta charset="utf-8">
<title>responsive circles</title>
<style>
body {
margin: 0;
}
#container {
padding: 5% 5%; /* (top & bottom) (left & right) */
width: 90%; /* container fits window (accommodates padding) */
background-color: #666;
}
#graphic {
background-color: #ccc;
}
</style>
<script src="https://d3js.org/d3.v4.min.js"></script>
<body>
<div id='container'></div>
<script>
var n = 6, // "n" random circles determine the SVG's aspect ratio
radii = d3.range(n).map(function(){ return Math.random(); }),
x = radii.map(function(d, i) { return d + 2 * d3.sum( radii.slice(0, i) ); }),
width = 2 * d3.sum(radii),
height = 2 * d3.max(radii);
var container = d3.select("#container");
var svg = container.append('svg')
.attr('id', 'graphic')
.attr('viewBox', "0, 0, " + width + ", " + height) // min-x, min-y, width, height
.attr('preserveAspectRatio', "xMinYMid");
svg.selectAll('circle')
.data(radii)
.enter()
.append('circle')
.attr('r', function(d) { return d; })
.attr('cx', function(d,i) { return x[i]; })
.attr('cy', height / 2)
.style('fill', function(d,i) { return d3.schemeCategory10[i]; });
// Set the container height explicitly (fixes IE problem)
setContainerHeight();
d3.select(window).on('resize', setContainerHeight);
function setContainerHeight() {
var w = parseInt( container.style("width"), 10); // computed width
var a = width / height; // = aspect ratio to be applied to the container
container.style('height', w / a + 'px');
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment