7👍
That is happening because, when you update chart (after changing title) by calling the update()
method, it re-renders the entire chart with an animation, which takes some time (approx. 1000 ms) to complete, making the chart update process delayed, and since this process is happening asynchronously, your image saving code executes even before the chart is updated completely, which makes the new title not show up on the exported image.
So basically, what you need is to update the chart without an animation (synchronously) , after changing the chart title and that could be done in either of two ways :
1. passing a config
object (argument) to the update
method with duration
property set to 0
:
chart_variable.update({
duration: 0
});
2. passing just 0
as argument to the update
method (see preventing animations) :
chart_variable.update(0);
var chart_variable = new Chart(ctx, {
type: 'line',
data: {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
datasets: [{
label: 'My First Dataset',
data: [3, 1, 4, 2, 5],
backgroundColor: 'rgba(0, 119, 290, 0.2)',
borderColor: 'rgba(0, 119, 290, 0.6)'
}]
},
options: {
title: {
display: true,
text: 'Chart Title'
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
stepSize: 1
}
}]
}
}
});
function downloadImage() {
/* set new title */
chart_variable.options.title.text = 'New Chart Title';
chart_variable.update({
duration: 0
});
// or, use
// chart_variable.update(0);
/* save as image */
var link = document.createElement('a');
link.href = chart_variable.toBase64Image();
link.download = 'myImage.png';
link.click();
/* rollback to old title */
chart_variable.options.title.text = 'Chart Title';
chart_variable.update({
duration: 0
});
// or, use
// chart_variable.update(0);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
<button onclick="downloadImage();">save as image</button>
<canvas id="ctx"></canvas>