Built with blockbuilder.org
xxxxxxxxxx
<meta charset="utf-8">
<head>
<title>Dynamic pie chart</title>
</head>
<style>
path {
stroke: white;
stroke-width: 2;
}
text {
font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;
font-size: .8em;
fill: white;
}
</style>
<body>
<svg width="960" height="520">
<g transform="translate(460, 240)"></g>
</svg>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"></script>
<script>
const fullCircle = 2 * Math.PI;
const slices = 5;
const radius = 220;
let arcData = arcDataGenerator(slices);
function arcDataGenerator(divider) {
const array = [];
let start = 0, end;
for(let i=0; i<divider; i++) {
const randNumber = Math.random() + .5;
const end = start + randNumber;
array.push({start: start, end: i===divider-1 ? fullCircle : end});
start = end;
}
return array;
}
function getPercentage(data) {
const multi = 100 / fullCircle;
return +((data.end - data.start) * multi).toFixed(2);
}
const colour = d3.scaleSequential()
.domain([0, 5])
.interpolator(d3.interpolatePlasma
);
const label = d3.arc()
.innerRadius(radius - 80)
.outerRadius(radius - 80)
.startAngle(function(d) {
return d.start;
})
.endAngle(function(d) {
return d.end;
});
const arc = d3.arc()
.innerRadius(0)
.outerRadius(radius)
.startAngle(function(d) {
return d.start;
})
.endAngle(function(d) {
return d.end;
});
d3.select('g')
.selectAll('path')
.data(arcData)
.enter()
.append('path')
.attr('d', arc)
.attr('fill', (d,i)=>colour(i));
const text = d3.select('g')
.selectAll('text')
.data(arcData)
.enter()
.append('text')
.text((d)=> `${getPercentage(d)+'%'}`)
.attr('text-anchor','middle')
.attr('x', d=>label.centroid(d)[0])
.attr('y', d=>label.centroid(d)[1]);
setInterval(()=> {
text.text((d)=> `${getPercentage(d)+'%'}`)
}, 100);
setInterval(()=> {
arcData = arcDataGenerator(slices);
text.text((d)=> `${getPercentage(d)+'%'}`)
.transition()
.duration(1800)
.attrTween("x", labelXTween)
.attrTween("y", labelYTween);
d3.select('g').selectAll("path")
.transition()
.duration(1800)
.attrTween("d", arcTween)
}, 4000);
function labelXTween(d, i, a) {
const interpolate_start = d3.interpolate(d.start, arcData[i].start)
const interpolate_end = d3.interpolate(d.end, arcData[i].end)
return function(t) {
d.start = interpolate_start(t);
d.end = interpolate_end(t);
return label.centroid(d)[0];
}
}
function labelYTween(d, i, a) {
const interpolate_start = d3.interpolate(d.start, arcData[i].start)
const interpolate_end = d3.interpolate(d.end, arcData[i].end)
return function(t) {
d.start = interpolate_start(t);
d.end = interpolate_end(t);
return label.centroid(d)[1];
}
}
function arcTween(d, i, a) {
const interpolate_start = d3.interpolate(d.start, arcData[i].start)
const interpolate_end = d3.interpolate(d.end, arcData[i].end)
return function(t) {
d.start = interpolate_start(t);
d.end = interpolate_end(t);
return arc(d);
}
}
</script>
</body>
</html
https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js