Strike
Strike

Reputation: 151

Chart.js multiple charts in same page(Working but still getting error)

Good Afternoon everyone. I'm trying to use to charts on the same page. It is working but I'm still getting an error in my console log:

Uncaught Error: Canvas is already in use. Chart with ID '1' must be destroyed before the canvas with ID 'rankingsActive' can be reused.

My HTML

<div>
  <canvas id="rankings" ></canvas>
</div>

<div>
  <canvas id="rankingsActive"></canvas>
</div>

My javascript code. I will post the first function that create my first chart. I have a similar function with the only difference being the last line. Different chart name and targeting my second canvas id

function rankingTypes(ranks) {
  //const labels = ["January", "February", "March", "April", "May", "June"]
  const data = {
    labels: Object.keys(ranks),
    datasets: [
      {
        label: "My First dataset",
        backgroundColor: "rgb(255, 99, 132)",
        borderColor: "rgb(255, 99, 132)",
        data: Object.values(ranks),
      },
    ],
  }
  console.log(data)
  console.log(Object.values(ranks))

  const config = {
    type: "pie",
    data: data,
  }

  const rankChart = new Chart(document.getElementById("rankings"), config)
}

Upvotes: 1

Views: 705

Answers (1)

LeeLenalee
LeeLenalee

Reputation: 31431

This means you already made a chart on that canvas, so you must destroy that one first. This can de done like so:

const c = Chart.getChart(canvasId);
if (c) c.destroy();

new Chart(canvasId, config);

Upvotes: 1

Related Questions