简体   繁体   中英

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)
}

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM