Chartjs-Switching between different Chart.js charts using the same canvas

0👍

Changing the chart type is such a fundamental difference that you need to completely destroy() the existing chart and then instantiate a new instance. Otherwise the defaults that Chart.js selected at instantiation are invalidated and this, as you noticed, causes some odd behaviour.

The following snippet demonstrates a way to do this:

let chart;

function mychart(type) {
  if (chart) {
    chart.destroy();
  }
  chart = new Chart(document.getElementById("chart"), {
    type: type,
    data: {
      labels: ["a", "b", "c", "d"],
      datasets: [{
        label: "Series1",
        data: [0, 1, 2, 4]
      }]
    }
  })
}

document.getElementById("line").addEventListener("click", function() {
  mychart("line");
});

document.getElementById("bar").addEventListener("click", function() {
  mychart("bar");
});

document.getElementById("doughnut").addEventListener("click", function() {
  mychart("doughnut");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
<p>
  <button id="line">Line</button>
  <button id="bar">Bar</button>
  <button id="doughnut">Doughnut</button>
</p>
<canvas id="chart"></canvas>

Leave a comment