[Chartjs]-My chart.js canvas disappears after hide() function

1👍

The reason this is happening is that your canvas’s parent, .library is hidden at the time of initialization, which sets the canvas height and width to 0. See this answer Canvas height/width 0

The solution is to first initialize the canvas and then hide the .library div. See code below:

$(function() {
  
  $("#hide").on("click", () => {
    $(".library").toggle();
  });


  var lineData = {
    labels: ["January", "February", "March", "April", "May", "June"],
    datasets: [{
      fillColor: "rgba(172,194,132,0.4)",
      strokeColor: "#ACC26D",
      pointColor: "#fff",
      pointStrokeColor: "#9DB86D",
      data: [186, 156, 251, 144, 305, 236]
    }]
  }
  var line = document.getElementById('line').getContext('2d');
  new Chart(line).Line(lineData);
  
  $(".library").hide();

})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js'></script>


<button id="hide">hide</button>
<div class="library" id="chart">

  <canvas id="line" width="600" height="400"></canvas>

</div>

Leave a comment