Initial Commit
This commit is contained in:
48
piechart.js
Normal file
48
piechart.js
Normal file
@@ -0,0 +1,48 @@
|
||||
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);
|
||||
Reference in New Issue
Block a user