I am using the Chart.js library to draw a bar graph, but I want to destroy the bar graph and make a new graph in the same canvas. I have tried this way to clear the canvas:
var chart = new Chart( ctx, {
type : "bar",
data : data1,
options : options
});
$("#btn1").on("click", function() {
if (chart) chart.destroy();
var chart = new Chart( ctx, {
type : "bar",
data : data1,
options : options
});
});
Am I calling it right? On ButtonClick I call this function which uses the same canvas.
<canvas id="graph" width="700px" height="300px"></canvas>
var ctx = $("#graph");
EDIT:
I change the code but only work for the first time I click in the button, when I change for the second time, it won't work again.
The trickiest is that to work I need to change the name of the 2 graph
var ctx = document.getElementById('graph');
var myChart = new Chart( ctx, {
type : "bar",
data : data1,
options : options
});
$("#btn2").on("click", function() {
if (myChart) myChart.destroy();
var ctx = document.getElementById('graph');
var chart = new Chart( ctx, {
type : "bar",
data : data2,
options : options
});
});
Thanks to all for the help but I already got it, and for future doubts, I will put my solution here to the people who need
var ctx = document.getElementById('graph').getContext('2d');
var myBarChart = new Chart( ctx, {
type : "bar",
data : data1,
options : options
});
$("#btn1").on("click", function() {
var context1 = document.getElementById('graph').getContext('2d');
if (myBarChart) myBarChart.destroy();
myBarChart = new Chart( context1, {
type : "bar",
data : data1,
options : options
});
});
$("#btn2").on("click", function() {
var context2 = document.getElementById('graph').getContext('2d');
if (myBarChart) myBarChart.destroy();
myBarChart = new Chart( context2, {
type : "bar",
data : data2,
options : options
});
});