<!DOCTYPE html>
<
html
lang
=
"en"
>
<
head
>
<
title
>Example 2</
title
>
<
script
src
=
</
script
>
</
head
>
<
body
>
<
center
>
<
h1
style
=
"color: green;"
>
GeeksforGeeks
</
h1
>
<
h3
>
Approach 2: Using Callbacks
</
h3
>
<
label
for
=
"ticksLimit"
>
Set Ticks Limit:
</
label
>
<
input
type
=
"number"
id
=
"ticksLimit"
value
=
"2"
min
=
"1"
max
=
"12"
>
<
button
onclick
=
"updateFn()"
>
Update Chart
</
button
>
<
canvas
id
=
"chart2"
></
canvas
>
</
center
>
<
script
>
const originalData =
[1200, 1500, 1800, 2000, 1700, 1900,
2200, 2500, 2800, 3000, 2700, 3200];
const data = {
labels:
['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
datasets: [{
label: 'Monthly Visitors',
data: originalData,
backgroundColor:
'rgba(75, 192, 192, 0.2)',
borderColor:
'rgba(75, 192, 192, 1)',
borderWidth: 2,
}]
};
const options = {
scales: {
x: {
ticks: {
callback: function (value, index, values) {
const ticksLimit =
document.getElementById('ticksLimit').value;
const interval =
Math.ceil(values.length / ticksLimit);
return index % interval === 0 ? value : '';
}
}
}
}
};
const ctx =
document.getElementById('chart2').getContext('2d');
const chart2 = new Chart(ctx, {
type: 'line',
data: data,
options: options
});
function updateFn() {
const newLimit =
parseInt(document.getElementById('ticksLimit').value);
if (newLimit >= 1 && newLimit <= 12) {
const interval =
Math.ceil(originalData.length / newLimit);
chart2.data.datasets[0].data =
originalData.filter((_, index) => index % interval === 0);
chart2.options.scales.x.ticks.callback =
function (value, index, values) {
return index % interval === 0 ? value : '';
};
chart2.update();
} else {
alert('Ticks limit should be between 1 and 12.');
}
}
</
script
>
</
body
>
</
html
>