Circle-packing tweets
xxxxxxxxxx
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="d3-forceextent.js"></script>
<style>
body { margin: 0; position: fixed; top: 0; right: 0; bottom: 0; left: 0; }
body {
font-family: monospace;
}
circle {
fill: teal;
stroke-width: 0;
}
.coin-text {
opacity: 0.5;
}
.counter {
font-size: 20px;
}
.animate {
color: black;
position: absolute;
top: 10px;
left: 10px;
}
</style>
</head>
<body>
<script>
var margin = { top: 50, right: 50, bottom: 50, left: 50 };
var width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var svg = d3.select("body").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 + ")");
var noOfCirclesA = 10;
noOfCirclesB =100;
var aPos = width / 7;
bPos = width - width / 4;
var te = d3.easeBounce;
var radius = 15;
var dataA = d3.range(noOfCirclesA);
dataA = dataA.map(function(d) {
return {
id: d
}
});
var dataB = d3.range(noOfCirclesB);
dataB = dataB.map(function(d) {
return {
id: d
}
});
var extent = [[0, width], [0, height]];
var simulationA = d3.forceSimulation(dataA)
.force("x", d3.forceX(aPos))
.force("y", d3.forceY(height))
.force("extent", d3.forceExtent(extent))
.force("collide", d3.forceCollide(radius + 2))
.stop();
var simulationB = d3.forceSimulation(dataB)
.force("x", d3.forceX(bPos))
.force("y", d3.forceY(height))
.force("extent", d3.forceExtent(extent))
.force("collide", d3.forceCollide(radius + 2))
.stop();
for (var i = 0; i < 120; ++i) simulationA.tick();
for (var i = 0; i < 120; ++i) simulationB.tick();
var counterA = 0,
counterB = 0;
var legendA = svg.append("g")
.append("text")
.attr("class", "counter")
.attr("x", aPos)
.attr("text-anchor", "middle")
.text(0);
var legendB = svg.append("g")
.append("text")
.attr("class", "counter")
.attr("x", bPos)
.attr("text-anchor", "middle")
.text(0);
function increment(pile) {
if (pile === "a") {
counterA++;
legendA.text(counterA);
} else {
counterB++;
legendB.text(counterB);
}
}
addCircles(dataA, "a");
addCircles(dataB, "b");
function addCircles(data, pile) {
var circle = svg.append("g")
.attr("class", "circles")
.selectAll("g").data(data)
.enter().append("g")
.attr("transform", function(d) {
return "translate(" + d.x + "," + (-margin.top - radius * 2) + ")"
});
circle.append("circle")
.attr("r", radius)
circle.append("text")
.attr("class", "coin-text")
.attr("text-anchor", "middle")
.attr("dy", radius / 3)
.text("£");
circle.transition()
.duration(750)
.delay(function(d, i) {
return (height - d.y) * 20;
})
// .ease(te)
.attr("transform", function(d) {
return "translate(" + d.x + ", " + d.y + ")";
})
.on("end", function() {
increment(pile);
});
}
</script>
</body>
https://d3js.org/d3.v4.min.js