Created
June 27, 2021 07:23
-
-
Save beiweiqiang/c19ed63adade2ed963c8d0be5f02d13f to your computer and use it in GitHub Desktop.
使用 svg 生成扇形图
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); |
Author
beiweiqiang
commented
Jun 27, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment