Skip to content

Instantly share code, notes, and snippets.

@h5ng
Last active September 19, 2017 05:56
Show Gist options
  • Save h5ng/bb766d1b97e36edf71a1f0f290967545 to your computer and use it in GitHub Desktop.
Save h5ng/bb766d1b97e36edf71a1f0f290967545 to your computer and use it in GitHub Desktop.
Rounded Donut Chart
<div id="chart"></div>
class Chart extends React.Component {
render() {
const width = this.props.width,
height = this.props.height,
radius = Math.min(width, height)/2,
data = this.props.value * 0.01,
arc = d3.arc()
.innerRadius(this.props.margin)
.outerRadius(radius)
.cornerRadius(this.props.margin)
.startAngle(0);
return (
<svg
id="rounded-chart"
width={width}
height={height}
>
<g
id="rounded-chart-group"
transform={"translate(" + width/2 + ", " + height/2 + ")"}
>
<path
id="background-chart"
fill={"#cccccc"}
d={arc({endAngle: 2 * Math.PI})}
>
</path>
<path
id="foreground-chart"
fill={"#c84b53"}
d={arc({endAngle: data * 2 * Math.PI})}
>
</path>
<text
id="chart-value"
textAnchor="middle"
style={{
fontSize: '20px',
fill: '#c84b53'
}}
>{this.props.value + '%'}</text>
</g>
</svg>
)
}
componentDidMount() {
const width = this.props.width,
height = this.props.height;
d3.select('#chart-value')
.attr("transform", function() {
const bbox = d3.select(this).node().getBBox();
return "translate(0, " + bbox.height/4 + ")";
})
}
}
ReactDOM.render(
<Chart value={60} width={83} height={83} margin={28}/>,
document.getElementById('chart')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.9.1/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.min.js"></script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment