How to render the same chart using Chart.js

0👍

Yes this is possible, you can just call the new chart in a for loop, make sure to save the chart instances so you can work with them later

example:

const charts = {
  options0: {
    type: 'line',
    data: {
      labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
      datasets: [{
          label: '# of Votes',
          data: [12, 19, 3, 5, 2, 3],
          borderWidth: 1
        },
        {
          label: '# of Points',
          data: [7, 11, 5, 8, 3, 7],
          borderWidth: 1
        }
      ]
    },
    options: {}
  },
  options1: {
    type: 'bar',
    data: {
      labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
      datasets: [{
          label: '# of Votes',
          data: [12, 19, 3, 5, 2, 3],
          borderWidth: 1
        },
        {
          label: '# of Points',
          data: [7, 11, 5, 8, 3, 7],
          borderWidth: 1
        }
      ]
    },
    options: {}
  },
  options2: {
    type: 'radar',
    data: {
      labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
      datasets: [{
          label: '# of Votes',
          data: [12, 19, 3, 5, 2, 3],
          borderWidth: 1
        },
        {
          label: '# of Points',
          data: [7, 11, 5, 8, 3, 7],
          borderWidth: 1
        }
      ]
    },
    options: {}
  }
}

let activeCharts = [];
for (let i = 0; i < Object.keys(charts).length; i++) {
  activeCharts.push(new Chart(document.getElementById(`con${i}`).getContext('2d'), charts[`options${i}`]));
}
<body>
  <canvas id="con0" width="600" height="400"></canvas>
  <canvas id="con1" width="600" height="400"></canvas>
  <canvas id="con2" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.2.0/chart.js" integrity="sha512-opXrgVcTHsEVdBUZqTPlW9S8+99hNbaHmXtAdXXc61OUU6gOII5ku/PzZFqexHXc3hnK8IrJKHo+T7O4GRIJcw==" crossorigin="anonymous"></script>
</body>

Leave a comment