简体   繁体   中英

Gantt Chart Timeline Chart js 3

Chart.js is a popular library for making charts, and it can make all kinds of charts, but it can't make a Gantt Chart/Timeline. I'm trying to hack chart.js 3, but the documentation isn't great and I'm getting really frustrated. How do you make a Gantt Chart Timeline with chart.js 3?

You do it like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Timeline chart.js 3</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>
</head>
<body>
<main>

    <canvas id="gantt-chart"></canvas>

    <script>
        data = [
            {id: 2, name: "Season Apples", start_date: "2022-03-07 15:00:00.000", end_date: "2022-03-10 15:00:00.000"},
            {id: 1, name: "Cut Apples", start_date: "2022-03-05 15:00:00.000", end_date: "2022-03-07 15:00:00.000"},
            {id: 3, name: "Bake Apples", start_date: "2022-03-11 15:00:00.000", end_date: "2022-03-15 15:00:00.000"}
        ]

        // sort objects by start_date
        data.sort(function (a, b) {
            return new Date(a.start_date) - new Date(b.start_date);
        });
        // chart js needs labels in separate array
        const labels = data.map(x => {
            return [x.name];
        })
        // transform the data from how the backend outputs it to how the chart js needs it
        const newData = data.map(x => {
            return [x.start_date.split(' ')[0], x.end_date.split(' ')[0]]
        });

        data = {
            labels: labels,
            datasets: [{
                label: 'Make Apple Recipe',
                data: newData,
                backgroundColor: 'rgba(255, 99, 132, 0.2)',
                borderColor: 'rgba(255, 99, 132, 1)',
                borderWidth: 1,
                fill: false,
                barPercentage: 0.3
            }]
        };

        options = {
            indexAxis: 'y',
            responsive: true,
            scales: {
                x: {
                    min: newData[0][0],
                    type: 'time',
                    time: {
                        unit: 'day'
                    }
                },
                y: {
                    beginAtZero: true,
                }
            }
        };

        new Chart(document.getElementById('gantt-chart').getContext('2d'), {
            type: 'bar', data: data, options: options
        });

    </script>
</main>

</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM