Chart.js icon indicating copy to clipboard operation
Chart.js copied to clipboard

Can't clear chart area

Open ekatherina opened this issue 10 years ago • 3 comments

I have page with chart and button. When I press button I clean canvas and redraw chart.

<script type="text/javascript">
    $(function () {
        var canvas3 = document.getElementById("сhart3");
        var ctx3 = canvas3.getContext("2d");

              $('#buttonId').click(function () {
                     CreateChart(data, canvas3, ctx3);
           });

               function CreateChart(sourceJson, canvas, context){
            context.clearRect(0,0,canvas.width,canvas.height)

            var lineChart = new Chart(context).Line(lineChartData, {
                                          responsive: true,
                                              other options...
            });
               }
    });
</script>

But it looks like second chart is drawn over fist chart. So when I mouse over ponts chart blinks. (it shows first chart in some points and second chart in other) But I always want to have only one chart. I mean clear previous chart and draw new one in the same canvas.

How I can clear you chart correcly?

ekatherina avatar Mar 28 '16 11:03 ekatherina

@ekatherina you need to keep track of the old chart and before creating the new one you need to do oldChart.destroy()

etimberg avatar Mar 28 '16 13:03 etimberg

Please, stop close that kind of items. It is realy an issue. Way you offer is very inconvenient. First of all, If I create new context for the same canvas I think it should forget about previous charts and as a result draw new charts in empty canvas.

But, if you can't do that, It will be very goot to have something like that var chartContext = new Chart(context); chartContext.clear(); chartContext.Line(lineChartData, { responsive: true, other options... });) Thank you. Kate.

ekatherina avatar Mar 29 '16 22:03 ekatherina

@ekatherina the issue isn't necessarily needing to clear the chart as that already happens.

The underlying problem is that the first chart that was created is still listening to events on the canvas node such as "mousemove", "touchstart", "touchmove", "mouseout". Since these events are on the canvas node and not the context, the listeners need to be removed before the canvas can be safely reused. The only way that this happens is in the destroy() method.

etimberg avatar Mar 29 '16 23:03 etimberg