CalorieCalculatorJS

Форк
0
77 строк · 3.1 Кб
1
import {canvas, storage} from "../variables.js";
2

3
// Отрисовка диаграммы
4
export const drawChart = (chartData) => {
5

6
    // Проверка наличия элемента canvas
7
    if (!canvas) {
8
        console.error('Canvas element not found');
9
        return;
10
    }
11

12
    // Получение контекста рисования на canvas
13
    const ctx = canvas.getContext('2d');
14
    // Очистка canvas
15
    ctx.clearRect(0, 0, canvas.width, canvas.height);
16

17
    // Определение параметров для рисования графиков
18
    const barWidth = 4;
19
    const spacing = 5;
20
    const chartHeight = canvas.height - 40;
21

22
    // Рисование каждой колонки на графике
23
    chartData.forEach((data, index) => {
24
        const x = index * (barWidth + spacing) * 2 + spacing;
25

26
        // Рисование синей колонки для потребленных калорий
27
        ctx.fillStyle = 'blue';
28
        const consumedHeight = (data.totalCalories / data.maxValue) * chartHeight / 5;
29
        ctx.fillRect(x, chartHeight - consumedHeight, barWidth, consumedHeight);
30

31
        // Рисование красной колонки для целевых калорий
32
        ctx.fillStyle = 'red';
33
        const targetHeight = (data.targetCalories / data.maxValue) * chartHeight / 5;
34
        ctx.fillRect(x + barWidth + spacing, chartHeight - targetHeight, barWidth, targetHeight);
35

36
        // Рисование даты под каждой колонкой
37
        ctx.fillStyle = 'black';
38
        ctx.font = '10px Arial';
39

40
        ctx.save();
41
        ctx.translate(x + barWidth / 2, canvas.height - 21);
42
        ctx.rotate(Math.PI / 3);
43
        ctx.fillText(data.date, 0, 0);
44
        ctx.restore();
45
    });
46
};
47

48
// Отрисовка графика
49
export const displayChart = () => {
50
    // Получение выбранных продуктов из localStorage
51
    let selectedProducts = JSON.parse(localStorage.getItem(storage.selectedProducts)) || [];
52

53
    // Преобразование данных для отображения на графике
54
    const chartData = selectedProducts.map(entry => {
55
        const totalCalories = entry.products.reduce((sum, productGroup) => {
56
            return sum + productGroup.reduce((productSum, product) => productSum + parseInt(product.calories), 0);
57
        }, 0);
58

59
        // Получение целей из localStorage
60
        const goals = JSON.parse(localStorage.getItem(storage.goals)) || [];
61
        // Поиск текущих целей для текущей даты
62
        const currentGoals = goals.find(goal => goal.date === entry.date);
63

64
        // Определение данных для графика
65
        const targetCalories = currentGoals ? parseInt(currentGoals.caloriesGoal) : 0;
66

67
        return {
68
            date: entry.date,
69
            totalCalories: totalCalories,
70
            targetCalories: targetCalories,
71
            maxValue: Math.max(totalCalories, targetCalories),
72
        };
73
    });
74

75
    // Отрисовка графика
76
    drawChart(chartData);
77
};

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.