Chart.js playground

by kikkoma

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.js"></script>
<div>
<canvas id="myChart" width="300" height="250"></canvas>
</div>

JavaScript

// 產生150到350之間的隨機數字
        function getRandomData(min, max, count) {
            const data = [];
            for (let i = 0; i < count; i++) {
                data.push(Math.floor(Math.random() * (max - min + 1)) + min);
            }
            return data;
        }

        // 生成指定年月的日期標籤
        function generateLabels(year, month) {
            const labels = [];
            const daysInMonth = new Date(year, month, 0).getDate();
            for (let day = 1; day <= daysInMonth; day++) {
                const formattedDay = day < 10 ? `${day}` : day;
                labels.push(`${month < 10 ? '' : ''}${month}/${formattedDay}`);
            }
            return labels;
        }

        const year = 2024;
        const month = 7; // 7表示7月
        const labels = generateLabels(year, month);

				const ctx = document.getElementById('myChart').getContext('2d');
        const myChart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: labels,
                datasets: [{
                    label: '單日存取統計',
                    data: getRandomData(150, 350, 29),
                    backgroundColor: 'rgba(54, 162, 235, 0.2)',
                    borderColor: 'rgba(54, 162, 235, 1)',
                    borderWidth: 1
                }]
            },
            options: {
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        });