Chartjs - How to Redraw or Update Charts Over and Over Again
Chartjs has its buinl-in update methond which can be used to add or remove data point and update the chart. But I have found another way to do so, which is to remove the canvas where the chart is graphed and create the same canvas.
If we don't remove the canvas before we redraw, we may see this error "Canvas is already in use. Chart with ID '0' must be destroyed before the canvas can be reused."
Sample HTML Code
<div id="chartwrap">
<canvas height="400" id="myChart" width="400"></canvas>
</div>
<script>
chartwrap.removeChild(document.getElementById('myChart'));
var newchart = document.createElement('canvas');
newchart.setAttribute('id','myChart');
chartwrap.appendChild(newchart);
</script>
Adding Data: Using orgainc update method
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<input id="inputdata" type="number" value="20" />
<button onclick="updatechart()">Add Date and Update Chart</button><br />
<canvas height="400" id="myChart" width="400"></canvas>
<script>
var datapoints = [12,22,15];
var inputdata = document.getElementById('inputdata');
var labels = [1,2,3];
var data = {
labels: labels,
datasets: [{
label: 'My First dataset',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: datapoints,
}]
};
const config = {
type: 'line',
data: data,
options: {
scales:{
y:{
ticks:{
font:{
size:15
}
}
}
},
plugins:{
legend:{
labels:{
font:{
size:15
}
}
}
}
}
};
const myChart = new Chart(
document.getElementById('myChart'),
config
);
function updatechart(){
var ll = datapoints.length;
addData(myChart, ll+1, parseInt(inputdata.value));
};
function addData(chart, label, data) {
chart.data.labels.push(label);
chart.data.datasets.forEach((dataset) => {
dataset.data.push(data);
});
chart.update();
};
</script>
Key Points
- The logic behind the organic way of updating chart is to push (add) or to pop (remove) data points.
- Chartjs data is in an array of object (data.datasets) which is why we loop through chart.data.datasets then doing array methods like push or pop on each dataset.data.
- Finally, we call chart.update() to update for the newly modified data.
- One problem with the organic way is that you can't redo the chart completely which is sometimes nessary. Then the first solution may be better.
- You can also use document.getElementById("someid").remove() to remove the chart and add it back.
- You can also use innerHTML of the chartwrap to recreate chart canvas for redrawing. The code is below:
<div id="chartwrap"> <canvas height="400" id="myChart" width="400"></canvas> </div> <script> chartwrap.innerHTML =`<canvas height="400" id="myChart" width="400"></canvas>`; </script>
Comments
Post a Comment