Destroy Chart.Js Bar Graph to Redraw Other Graph in Same <Canvas>

Destroy chart.js bar graph to redraw other graph in same <canvas>

The correct method to use, in order to be able to draw another chart on the same canvas, is .destroy(). You must call it on the previously created chart object. You may also use the same variable for both charts.

var grapharea = document.getElementById("barChart").getContext("2d");

var myChart = new Chart(grapharea, { type: 'bar', data: barData, options: barOptions });

myChart.destroy();

myChart = new Chart(grapharea, { type: 'radar', data: barData, options: barOptions });

Straight from the docs (under Prototype Methods):

.destroy()

Use this to destroy any chart instances that are created. This will clean up any references stored to the chart object within Chart.js, along with any associated event listeners attached by Chart.js. This must be called before the canvas is reused for a new chart.

// Example from the docs
var myLineChart = new Chart(ctx, config);
// Destroys a specific chart instance
myLineChart.destroy();

It explicitly states that this method must be called before the canvas can be reused for a new chart.

.clear() is also mentioned later in the same section as the function that "will clear the chart canvas. Used extensively internally between animation frames, but you might find it useful." The chart will be alive and well after calling this method, so this is not the method to call, if you want to reuse the canvas for a brand new chart.

To be honest, though, in cases like yours, I have often used a container div to wrap my canvas and, whenever I needed to create a new chart, I placed a new canvas element in this div. I then used this newly created canvas for the new chart. If you ever come across strange behavior, possibly related to charts occupying the canvas before the current chart, have this approach in mind too.

Destroy chart.js bar graph to redraw other graph

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
});
});

How to clear a chart from a canvas so that hover events cannot be triggered?

I had huge problems with this

First I tried .clear() then I tried .destroy() and I tried setting my chart reference to null

What finally fixed the issue for me: deleting the <canvas> element and then reappending a new <canvas> to the parent container


My specific code (obviously there's a million ways to do this):

var resetCanvas = function(){
$('#results-graph').remove(); // this is my <canvas> element
$('#graph-container').append('<canvas id="results-graph"><canvas>');
canvas = document.querySelector('#results-graph');
ctx = canvas.getContext('2d');
ctx.canvas.width = $('#graph').width(); // resize to parent width
ctx.canvas.height = $('#graph').height(); // resize to parent height
var x = canvas.width/2;
var y = canvas.height/2;
ctx.font = '10pt Verdana';
ctx.textAlign = 'center';
ctx.fillText('This text is centered on the canvas', x, y);
};

How to 'destroy' previous chart (canvas) after new one is shown | Angular 4

Seems like you are using the ChartJS library. In that case, you can use the destroy() method to destroy any previous instance of chart.

ꜰɪʀꜱᴛ

add a property (in which the chart instance gonna be stored) in your chart component class :

public myChart: Chart

ꜱᴇᴄᴏɴᴅ

check and destroy the chart instance (if any) before creating a new one :

...
if (this.myChart) this.myChart.destroy(); //destroy prev chart instance
this.myChart = new Chart(this.ctx, {
type: 'bar',
data: this.barChartData,
...

How to Reset a Chart of Chart.Js?

That is because you are creating a new instance of chart.js every time you call the function, create a outiside var chart:

   var chart;
function cargar_datos(datasL,dataP,dataR){
var ctx = $("#myChart")
chart = new Chart(ctx, {
type: 'line',
data:
{
labels: datasL,
datasets:
[{
label: "Rendimiento",
borderColor: 'rgb(255, 99, 132)',
backgroundColor: ['rgba(255,200,200,0)'],
borderWidth: 2,
pointBackgroundColor: "red",
pointBorderColor: "rgba(250,10,10,0.1)",
pointBorderWidth: "10",
pointStyle: "rectRounded",
data:dataP,
},
{
label: "Aplicado",
borderColor: 'rgb(0, 143, 255)',
backgroundColor: ['rgba(112, 171, 219, 0.2)'],
borderWidth: 2,
pointBackgroundColor: "blue",
pointBorderColor: "rgba(144, 140, 174, 0.3)",
pointBorderWidth: "10",
pointStyle: "rectRounded",
data: dataR
}]
},
options: {
tooltips: {
position: 'average',
mode: 'index',
intersect: false,
},
}
});
chart.destroy();
}

chartjs removing/redrawing canvas, graph not responsive

it's important to note that .destroy() or .clear() methods dont fit my
needs!

I think there's something wrong going on here. The underlying problem here is that you are not destroying the chart you created first i.e. testChart. Simply removing the node does not clean it up completely.


Chart.js internally stores all instances of the charts created. When you resize the window, Chart.js loops through this list running a resize on each instance. In your code above, it errors out because the first instance is no longer in the DOM and the resize is never triggered for the 2nd instance testChart2

I'd strongly suggest you evaluate why you can't do a .destroy() (this simply removes the instance from Chart.js internal list) before doing the .remove().

However, if there is some reason you can't call a .destroy(), you can do one of the below


Option 1

Write your own window resize handler that triggers resize for the chart instances you want, like so

Chart.helpers.addEvent(window, "resize", (function () {
var timeout;
return function () {
clearTimeout(timeout);
timeout = setTimeout(function () {
myLineChart1.resize(myLineChart1.render, true);
}, 50);
};
})());

Option 2

Rewrite the getMaximumWidth function in the Chart.js library to add a try catch block, like so (just search for the first line to locate the block)

getMaximumWidth = helpers.getMaximumWidth = function (domNode) {
try {
var container = domNode.parentNode;
// TODO = check cross browser stuff with this.
return container.clientWidth;
}
catch (err)
{}
},

Option 3

Remove the responsive option for the chart before removing it's node, like so

myLineChart.options.responsive = false;
$("#testLine").remove();

While this doesn't remove the unnecessary reference from the Chart.js internal list, it prevents Chart.js from triggering an (unnecessary) error causing resize for an instance that doesn't exist in the DOM.


Here's Option 3 in action

Fiddle - https://jsfiddle.net/0vfqw61q/



Related Topics



Leave a reply



Submit