Skip to content

Instantly share code, notes, and snippets.

@QuadFlask
Created January 28, 2021 02:50
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 QuadFlask/899ddcfa109fab57b1b67f15cfb5dd2a to your computer and use it in GitHub Desktop.
Save QuadFlask/899ddcfa109fab57b1b67f15cfb5dd2a to your computer and use it in GitHub Desktop.
donut chart using svg
const DonutChart: FC<{
size: number;
data: {
value: number;
color: string;
}[];
strokeWidth?: number;
bgColor?: string;
}> = ({size, strokeWidth = 10, bgColor, data}) => {
const cx = size / 2;
const cy = size / 2;
const radius = (size - strokeWidth) / 2;
let start = 0;
return <svg width={size} height={size}>
<circle cx={cx} cy={cy} r={radius} stroke={bgColor || "#eee"} fill="transparent" strokeWidth={strokeWidth}/>
{
data.map(d => {
const c = <Arc size={size} start={start} amount={d.value} strokeWidth={strokeWidth} strokeColor={d.color}/>
start += d.value;
return c;
}).reverse()
}
</svg>
}
function toRad(degree: number) {
return degree / 180 * Math.PI;
}
const Arc: FC<{
size: number;
start: number;
amount: number;
strokeWidth?: number;
strokeColor?: string;
}> = ({size, start, amount, strokeWidth = 10, strokeColor}) => {
const cx = size / 2;
const cy = size / 2;
const radius = (size - strokeWidth) / 2;
const startAngle = -90 + start * 360;
const endAngle = Math.min(amount * 360, 359.999);
const startX = Math.cos(toRad(startAngle)) * radius;
const startY = Math.sin(toRad(startAngle)) * radius;
const endX = cx + Math.cos(toRad(startAngle + endAngle)) * radius;
const endY = cy + Math.sin(toRad(startAngle + endAngle)) * radius;
const large = endAngle >= 180 ? 1 : 0;
return <path d={`M ${cx + startX} ${cy + startY} A ${radius} ${radius} 0 ${large} 1 ${endX} ${endY}`}
stroke={strokeColor} strokeWidth={strokeWidth}
strokeLinecap="round" fill="#0000"/>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment