Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chart.js Disappear on Window Resize

I'm using Chart.js to display a line chart in a div which is within a <tr>.

<tr class="item">...</tr>
<tr class="item-details">
...
    <div class="col-sm-6 col-xs-12 chart-pane">
        <div class="chart-container">
            ...
            <div><canvas id="future-chart"></canvas></div>
        </div>
    </div>
...
</tr>

When the page is loaded, the item-details <tr> is hidden, and clicking on the item <tr> above it will make it show as well as call a function to draw the chart in the canvas. This function is shown below:

$(document).on('click', '.item', function(){
    var itemDetails = $(this).closest('tr').next('tr');
    ...
    var canvas = itemDetails.find('#future-chart').get(0);

    if (canvas) {
        ...
        // just setting data here
        var data = { 
            ...
        };
        var options = {
            responsive: true,
            maintainAspectRatio: true
        };  
        var futureChart = new Chart(context).Line(data,options);
    }   
}); 

The problem I'm having is that if I click the div to show when the screen is larger than 767px (), then click again to hide, resize the screen to less than 767px, and open the tr again, the chart is gone.

This is the only case I can find which makes the chart disappear. If I do the opposite of the above, the chart stays there. If I leave the <tr> open and resize the window, the chart stays just fine.

I have Responsive set to True and the chart resizes correctly when the <tr> is open and I resize the window.

I was thinking I needed to re-draw the canvas when the window is resized, however the entire chart is supposed to be re-drawn whenever the <tr> is opened, so I'm not sure exactly what is causing this.

like image 946
Ryan McClure Avatar asked Jan 30 '16 20:01

Ryan McClure


1 Answers

I had a problem, on resizing the window, the graph disappears. I solved the problem by creating the graph just once with the new command

this.myChart = new Chart(this.ctx, {
      type: 'line', .....
}

After that, I only do update() on the created chart. indeed, creating a chart each time is not kept in memory. Example to update the datasets

this.myChart.data.datasets = datasetsTmp;
this.myChart.update();

I hope it's help.

like image 199
nai Avatar answered Sep 20 '22 04:09

nai