7👍
✅
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>
Source:stackexchange.com