Skip to content

Instantly share code, notes, and snippets.

@beiweiqiang
Created June 27, 2021 07: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 beiweiqiang/c19ed63adade2ed963c8d0be5f02d13f to your computer and use it in GitHub Desktop.
Save beiweiqiang/c19ed63adade2ed963c8d0be5f02d13f to your computer and use it in GitHub Desktop.
使用 svg 生成扇形图
function buildSvg(arr) {
return arr.reduce((acc, itm, idx) => {
const { path, fill } = itm;
return acc += `<path d="${path}" fill="${fill}" />`;
}, '');
}
function getPathString(option) {
const { x, y, r, sectors } = option;
const arr = [];
for (let sector of sectors) {
let path = `M${x} ${y}`;
const { start, end, fill } = sector;
const startX = x + Math.sin(toDegrees(start)) * r;
const startY = y - Math.cos(toDegrees(start)) * r;
const endX = x + Math.sin(toDegrees(end)) * r;
const endY = y - Math.cos(toDegrees(end)) * r;
path += ` L${startX} ${startY} A${r} ${r} 0 ${end - start > 180 ? 1 : 0} 1 ${endX} ${endY} L${x} ${y} Z`
arr.push({ path, fill })
}
return arr;
}
function toDegrees (angle) {
return angle * (Math.PI / 180);
}
const a = getPathString({
x: 300,
y: 300,
r: 50,
sectors: [
{ start: 0, end: 60, fill: '#4287f5' },
{ start: 60, end: 80, fill: '#42f59e' },
{ start: 80, end: 120, fill: '#cf72b4' },
{ start: 120, end: 360, fill: '#cf9772' },
]
});
console.log(buildSvg(a));
@beiweiqiang
Copy link
Author

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment