Я нашел работу другого человека, где он создает круговую диаграмму из массива. в javascript, за исключением того, что он основан на процентах.
Я пытался переделать его так, чтобы оно:
- Берет значение из массива
- Делит на сумму в массиве
- Использует этот процент как площадь
Мой цель состоит в том, чтобы заменить все проценты: x на значение: y, чтобы вы могли использовать необработанные значения:
Код: Выделить всё
const slices = [
{ value: 1024 },
{ value: 5684 },
{ value: 125 },
];
let sum = slices.reduce(function (a, b) {
return a + b.value
}, 0);
Код: Выделить всё
// variables
const svgEl = document.querySelector('svg');
const slices = [
{ percent: 0.1, color: 'red' },
{ percent: 0.1, color: 'blue' },
{ percent: 0.1, color: 'green' },
];
let cumulativePercent = 0;
// coordinates
function getCoordinatesForPercent(percent) {
const x = Math.cos(2 * Math.PI * percent);
const y = Math.sin(2 * Math.PI * percent);
return [x, y];
}
// loop
slices.forEach(slice => {
// destructuring assignment sets the two variables at once
const [startX, startY] = getCoordinatesForPercent(cumulativePercent);
// each slice starts where the last slice ended, so keep a cumulative percent
cumulativePercent += slice.percent;
const [endX, endY] = getCoordinatesForPercent(cumulativePercent);
// if the slice is more than 50%, take the large arc (the long way around)
const largeArcFlag = slice.percent > 0.5 ? 1 : 0;
// create an array and join it just for code readability
const pathData = [
`M ${startX} ${startY}`, // Move
`A 1 1 0 ${largeArcFlag} 1 ${endX} ${endY}`, // Arc
`L 0 0`, // Line
].join(' ');
// create a and append it to the element
const pathEl = document.createElementNS('http://www.w3.org/2000/svg', 'path');
pathEl.setAttribute('d', pathData);
pathEl.setAttribute('fill', slice.color);
svgEl.appendChild(pathEl);
});Код: Выделить всё
svg {
height: 200px;
}Код: Выделить всё
Подробнее здесь: https://stackoverflow.com/questions/664 ... -pie-chart
Мобильная версия