Reputation: 871
I have an array of charts on the page called charts
. This is the code I tried to run to make the font change:
for(var x in charts){
charts[x].options.scales.yAxes[0].ticks.fontSize = 20;
charts[x].options.scales.xAxes[0].ticks.fontSize = 20;
charts[x].update();
}
I know that I am correctly reaching the fontSize
attribute because in the console it returns the right font size to me. After I change the fontSize, it returns the correct one. For some reason, however, the actual charts aren't updating. Is the chart.update
command only made for updating data?
Note: This question is not a duplicate of the other question that exists about dynamically updating charts with JS because the ChartJS version I am using is 2.7.
Upvotes: 3
Views: 5605
Reputation: 32889
In ChartJS version 2.7.0 or later, changing (dynamically) the font-size of chart axis' ticks by just setting the fontSize
property of ticks
won't actually apply to the chart. It will only add empty spaces for newly set font-size to the axis'.
In order to change the font-size of chart axis' ticks properly (which would apply to the chart), you will need to set fontSize
property for the minor
object (under ticks
) , like so :
for (var x in charts) {
// set/change the actual font-size
charts[x].options.scales.xAxes[0].ticks.minor.fontSize = 20;
charts[x].options.scales.yAxes[0].ticks.minor.fontSize = 20;
// set proper spacing for resized font
charts[x].options.scales.xAxes[0].ticks.fontSize = 20;
charts[x].options.scales.yAxes[0].ticks.fontSize = 20;
// update chart to apply new font-size
charts[x].update();
}
ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ ⧩
var myChart1 = new Chart(ctx1, {
type: 'line',
data: {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
datasets: [{
label: 'Profit',
data: [30, 10, 40, 20, 50],
backgroundColor: 'rgba(61, 208, 239, 0.2)',
borderColor: 'rgba(61, 208, 239, 0.6)'
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
var myChart2 = new Chart(ctx2, {
type: 'line',
data: {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
datasets: [{
label: 'Loss',
data: [50, 20, 40, 10, 30],
backgroundColor: 'rgba(239, 92, 61, 0.2)',
borderColor: 'rgba(239, 92, 61, 0.6)'
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
var charts = [myChart1, myChart2];
function changeFontSize() {
for (var x in charts) {
// set/change the font-size
charts[x].options.scales.xAxes[0].ticks.minor.fontSize = 20;
charts[x].options.scales.yAxes[0].ticks.minor.fontSize = 20;
// set proper spacing for resized font
charts[x].options.scales.xAxes[0].ticks.fontSize = 20;
charts[x].options.scales.yAxes[0].ticks.fontSize = 20;
// update chart to apply new font-size
charts[x].update();
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.0/Chart.min.js"></script>
<button onclick="changeFontSize();">Change Font Size</button>
<canvas id="ctx1"></canvas>
<canvas id="ctx2"></canvas>
Upvotes: 7