CalorieCalculatorJS
77 строк · 3.1 Кб
1import {canvas, storage} from "../variables.js";2
3// Отрисовка диаграммы
4export const drawChart = (chartData) => {5
6// Проверка наличия элемента canvas7if (!canvas) {8console.error('Canvas element not found');9return;10}11
12// Получение контекста рисования на canvas13const ctx = canvas.getContext('2d');14// Очистка canvas15ctx.clearRect(0, 0, canvas.width, canvas.height);16
17// Определение параметров для рисования графиков18const barWidth = 4;19const spacing = 5;20const chartHeight = canvas.height - 40;21
22// Рисование каждой колонки на графике23chartData.forEach((data, index) => {24const x = index * (barWidth + spacing) * 2 + spacing;25
26// Рисование синей колонки для потребленных калорий27ctx.fillStyle = 'blue';28const consumedHeight = (data.totalCalories / data.maxValue) * chartHeight / 5;29ctx.fillRect(x, chartHeight - consumedHeight, barWidth, consumedHeight);30
31// Рисование красной колонки для целевых калорий32ctx.fillStyle = 'red';33const targetHeight = (data.targetCalories / data.maxValue) * chartHeight / 5;34ctx.fillRect(x + barWidth + spacing, chartHeight - targetHeight, barWidth, targetHeight);35
36// Рисование даты под каждой колонкой37ctx.fillStyle = 'black';38ctx.font = '10px Arial';39
40ctx.save();41ctx.translate(x + barWidth / 2, canvas.height - 21);42ctx.rotate(Math.PI / 3);43ctx.fillText(data.date, 0, 0);44ctx.restore();45});46};47
48// Отрисовка графика
49export const displayChart = () => {50// Получение выбранных продуктов из localStorage51let selectedProducts = JSON.parse(localStorage.getItem(storage.selectedProducts)) || [];52
53// Преобразование данных для отображения на графике54const chartData = selectedProducts.map(entry => {55const totalCalories = entry.products.reduce((sum, productGroup) => {56return sum + productGroup.reduce((productSum, product) => productSum + parseInt(product.calories), 0);57}, 0);58
59// Получение целей из localStorage60const goals = JSON.parse(localStorage.getItem(storage.goals)) || [];61// Поиск текущих целей для текущей даты62const currentGoals = goals.find(goal => goal.date === entry.date);63
64// Определение данных для графика65const targetCalories = currentGoals ? parseInt(currentGoals.caloriesGoal) : 0;66
67return {68date: entry.date,69totalCalories: totalCalories,70targetCalories: targetCalories,71maxValue: Math.max(totalCalories, targetCalories),72};73});74
75// Отрисовка графика76drawChart(chartData);77};