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);
};
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 '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,
...
chartjs hover over data without hoveringing on line
Yes, you can set intersect
to false
in the tooltip config:
var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderColor: 'orange'
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderColor: 'pink'
}
]
},
options: {
plugins: {
tooltip: {
intersect: false
}
}
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.js"></script>
</body>
chart.js load totally new data
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
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'); // why use jQuery?
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);
};
Chart JS: Old chart data not clearing
This is because internally chart.js still populates the labels array so you will need to clear that one before replacing your data:
chart.data.labels = [];
chart.data.datasets[0].data = newData;
chart.update();
const options = {
type: 'line',
data: {
datasets: [{
label: '# of Votes',
data: [{
x: 'hi',
y: 5
}, {
x: 'test',
y: 10
}, {
x: 'end',
y: 2
}],
borderColor: 'pink'
}]
},
options: {}
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
const chart = new Chart(ctx, options);
chart.data.labels = [];
chart.data.datasets[0].data = [{
x: 'k',
y: 1
}, {
x: 't',
y: 4
}, {
x: 'a',
y: 5
}];
chart.update();
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.js"></script>
</body>
ChartJS v3.X - Limit the string size of label on canvas, without changing tooltip hover string
After wasting many hours I found a "Tip" highlight on the documentation that should be in the examples, and not just badly highlighted on the "Labeling Axes" page.
When you do a callback for ticks on the chart options settings, you get 3 params to call:
function(value, index, ticks)
I tried in many ways to change the last one because it is the array of all ticks with their labels, and it is the only one where the label string appears so I was trying to modify it.
You'd think at first that the "value" parameter is the one to be changed, but it returns the exactly same integer value as the "index" parameter on each callback iteration, so I thought the only one the I could manipulate to change the string was the "ticks" array, but I was completely wrong.
You actually need to call a special function called getLabelForValue()
.
The working code ended up like this:
const configTotal = {
type: 'bar',
data: dataTotal,
options: {
scales: {
y: {
beginAtZero: true
},
x: {
ticks: {
callback: function(value, index, ticks_array) {
let characterLimit = 12;
let label = this.getLabelForValue(value);
if ( label.length >= characterLimit) {
return label.slice(0, label.length).substring(0, characterLimit -1).trim() + '...';
}
return label;
}
}
}
}
},
};
I hope this helps anyone having the same problem as me.
Maybe all the time I wasted is all on me for not reading every single line with more patience, but in my opinion, this documentation lacks a lot more example codes for accessing properties and callback parameters and it's object values, the way it is just showing the type of object and returns of each class method call, makes it very confusing for non-experienced on chart.js users.
Related Topics
How to Convert HTML Table to Excel with Multiple Sheet
Accessing Localstorage from a Webworker
How to Abort Image <Img> Load Requests Without Using Window.Stop()
Bootstrap V2 Dropdown Navigation Not Working on Mobile Browsers
How to Escape a String Inside JavaScript Code Inside an Onclick Handler
How to Add Background-Image Using Ngstyle (Angular2)
How to Store a Byte Array in JavaScript
Download Textarea Contents as a File Using Only JavaScript (No Server-Side)
Is It Ok to Add Your Own Attributes to HTML Elements
React: Why Child Component Doesn't Update When Prop Changes
Jquery VS Document.Queryselectorall
Html/Javascript: Simple Form Validation on Submit
Scale Element Proportional to Background Cover with Jquery
Getting Selected Text Position