This demo explicitly sets the container height, which make a dynamic SVG graphic responsive (based on this stackoverflow answer).
Note: This solves a problem with IE.
This demo explicitly sets the container height, which make a dynamic SVG graphic responsive (based on this stackoverflow answer).
Note: This solves a problem with IE.
<!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> |