[Chartjs]-Access a chart in a different function

3👍

For a chart initialized like so

var myNewChart = new Chart(ctx).Line(data);

myNewChart.chart.canvas is your canvas object. Note that you’ll have to handle the redraws that happen for tooltip display / removal, animation (initial draw, if enabled) and chart resizes.

While you can also access the canvas using document.getElementById("myId") and the context using document.getElementById("myId").getContext("2d"), you won’t have access to the chart functions like .update(), .addData(), etc.. For this you need the chart instance.

Since every available chart instance is also stored in Chart.instances (and since Chart is global), you could do something like so

for (instance in Chart.instances) { 
    if (Chart.instances[instance].chart.canvas === document.getElementById("myId")) {
        console.log("found my chart instance")
        console.log(Chart.instances[instance])
    }
}

to get the chart instance.

Leave a comment