49 lines
1.5 KiB
JavaScript
49 lines
1.5 KiB
JavaScript
const segments = [
|
|
{ label: "Pantry", value: 104, color: getRandomColor() },
|
|
{ label: "Fridge", value: 30, color: getRandomColor() },
|
|
{ label: "Freezer", value: 87, color: getRandomColor() }
|
|
];
|
|
|
|
const totalValue = segments.reduce((accumulator, current) => {
|
|
return accumulator + current.value;
|
|
}, 0);
|
|
|
|
const circumference = 2 * Math.PI * 10;
|
|
|
|
function renderPieChart(data) {
|
|
let currentOffset = 0;
|
|
|
|
data.forEach((item, index) => {
|
|
const fraction = item.value / totalValue;
|
|
const segmentLength = fraction * circumference;
|
|
const circle = document.getElementById(`seg-${index + 1}`);
|
|
circle.style.strokeDasharray = `${segmentLength} ${circumference}`;
|
|
circle.style.strokeDashoffset = -currentOffset;
|
|
circle.style.stroke = item.color;
|
|
currentOffset += segmentLength;
|
|
addLegendItem(item);
|
|
});
|
|
}
|
|
|
|
function addLegendItem(item) {
|
|
const legend = document.getElementById('legend');
|
|
const div = document.createElement('div');
|
|
div.className = 'legend-item';
|
|
div.innerHTML = `
|
|
<span class="dot" style="background:${item.color}"></span>
|
|
<span>${item.label}: <strong>${item.value}</strong></span>
|
|
`;
|
|
legend.appendChild(div);
|
|
}
|
|
|
|
function getRandomColor() {
|
|
const letters = '0123456789ABCDEF';
|
|
let color = '#';
|
|
for (let i = 0; i < 6; i++) {
|
|
color += letters[Math.floor(Math.random() * 10)];
|
|
}
|
|
return color;
|
|
}
|
|
|
|
renderPieChart(segments);
|