<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<!-- 3.9.1-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.min.js" type="text/javascript"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js" type="text/javascript"></script>
<div class="chartBox">
<canvas id="myChart" width="400" height="400"></canvas>
<button onclick="timeFrame(this)" value="day">Day</button>
<button onclick="timeFrame(this)" value="week">Week</button>
<button onclick="timeFrame(this)" value="month">Month</button>
</div>
<script>
const day = [
{ x: Date.parse('2021-11-01 00:00:00 GMT+0800'), y: 18 },
{ x: Date.parse('2021-11-02 00:00:00 GMT+0800'), y: 12 },
{ x: Date.parse('2021-11-03 00:00:00 GMT+0800'), y: 1 }
];
const week = [
{ x: Date.parse('2021-10-31 00:00:00 GMT+0800'), y: 18 },
{ x: Date.parse('2021-11-02 00:00:00 GMT+0800'), y: 87 },
{ x: Date.parse('2021-11-03 00:00:00 GMT+0800'), y: 10 }
];
const month = [
{ x: Date.parse('2021-10-31 00:00:00 GMT+0800'), y: 18 },
{ x: Date.parse('2021-11-02 00:00:00 GMT+0800'), y: 87 },
{ x: Date.parse('2021-12-03 00:00:00 GMT+0800'), y: 10 }
];
console.log(day);
// setup
const data = {
//labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
datasets: [{
label: 'Weekly Sales',
data: day,
//data: [18, 12, 6, 9, 12, 3, 9],
backgroundColor: [
'rgba(255, 26, 104, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)',
'rgba(0, 0, 0, 0.2)'
],
borderColor: [
'rgba(255, 26, 104, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)',
'rgba(0, 0, 0, 1)'
],
borderWidth: 1
}]
};
// config
const config = {
type: 'bar',
data,
options: {
scales: {
x: {
type: 'time',
time: {
unit: 'month'
}
},
y: {
beginAtZero: true
}
}
}
};
// render init block
const myChart = new Chart(
document.getElementById('myChart'),
config
);
function timeFrame(period) {
//console.log(period)
//console.log(period.value)
if(period.value == 'day') {
myChart.config.options.scales.x.time.unit = period.value;
myChart.config.data.datasets[0].data = day;
}
if(period.value == 'week') {
myChart.config.options.scales.x.time.unit = period.value;
myChart.config.data.datasets[0].data = week;
}
if(period.value == 'month') {
myChart.config.options.scales.x.time.unit = period.value;
myChart.config.data.datasets[0].data = month;
}
myChart.update();
}
</script>