Skip to content

Instantly share code, notes, and snippets.

@sebastianrothbucher
Last active September 23, 2017 15:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sebastianrothbucher/ea7684fc1fbb771701f92dd2f88f10ad to your computer and use it in GitHub Desktop.
Save sebastianrothbucher/ea7684fc1fbb771701f92dd2f88f10ad to your computer and use it in GitHub Desktop.
react (and d3) pie with animation
<div id="pie"></div>
let dt=[5, 8, 15];
let colors=['green', 'blue', 'orange'];
let arcStart=(i) => {
let share=dt
.filter((_n, _i) => _i<i)
.reduce((_s, _n) => _s+_n, 0);
let all=dt
.reduce((_s, _n) => _s+_n, 0);
return [
40*Math.cos(2*Math.PI*share/all-Math.PI/2),
40*Math.sin(2*Math.PI*share/all-Math.PI/2),
(dt[i-1]>(all/2))
]; // [x, y, large], starting at 12 clockwise - PUH!
}
// our class
class Pie extends React.PureComponent { // need uppercase ;-)
render() { return (
<svg height={100} width={200}>
<g transform="translate(50, 50)">
/* manually (scale is from 0/0, so translate instead of chg coords) */
{dt.map((n, i) => (
<path d={'M 0 0 L '+arcStart(i).slice(0, 2).join(' ')+' A 40 40 0 '+(arcStart(i+1)[2]?1:0)+' 1 '+arcStart(i+1).slice(0, 2).join(' ')+' Z'} fill={colors[i]}></path>
))}
</g>
/* with a little help */
<g transform="translate(150, 50)">
{d3.pie()(dt).map(d3.arc().outerRadius(40).innerRadius(0)).map((a, i) => <path d={a} fill={colors[i]}></path>)} /* pie and arc returns fct (likewise e.g.: scale, color, ... - poss. many advanced ones like circle packing or scale, etc.) */
</g>
</svg>);
}
}
// finally: render
ReactDOM.render(<Pie/>, document.getElementById('pie'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.5.0/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.min.js"></script>
path {
transform: scale(1);
transition: transform 1s;
}
path:hover {
transform: scale(1.2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment