如何检索非全局图表实例

问题描述 投票:0回答:1

我正在使用chart.js像这样创建10个图表:

    new Chart(document.getElementById("chart01"), {
      type: 'doughnut',
      data: data,
      options: options
    });

    new Chart(document.getElementById("chart02"), {
      type: 'doughnut',
      data: data,
      options: options
    });

如您所见,我不使用var chart01 = new Chart(...,因为我不想全局拥有所有这些图表。

但是,我确实知道将图表分配到的画布ID。那么,如何使用此画布ID获取图表实例并进行更新?

此代码为我提供了所有Chart实例,但我不知道如何直接分配图表实例。

    Chart.helpers.each(Chart.instances, function(instance){
      console.log(instance.chart);
    })

非常感谢您的帮助。

chart.js
1个回答
0
投票

我从不使用这个想法/技巧(使用全局图表更容易。)>

无论如何,一种选择是将(if)或(switch case)放入循环内:

Chart.helpers.each(Chart.instances, function(instance){
  if (instance.chart.canvas.id === "chart_1") {
    console.log("id:"  + instance.chart.canvas.id +" | labels: " + instance.chart.data.labels);
    return;
  }
})

在我看来,此代码不是“那么干净”(对于10个图表)。我更喜欢使用new构造函数(也许别人得到了“更干净”的解决方案)。无论如何,这个想法会奏效。

代码示例

https://www.chartjs.org/docs/latest/developers/api.html#updateconfig

[chart_1february的数据集值从30更新为50

var chart_1 = document.getElementById('chart_1');
new Chart(chart_1, {
  // The type of chart we want to create
  type: 'line',
  responsive: true,
  // The data for our dataset
  data: {
    labels: ['January', 'February', 'March'],
    datasets: [{
      label: 'My First dataset',
      backgroundColor: 'rgb(255, 99, 132)',
      borderColor: 'rgb(255, 99, 132)',
      data: [20, 30, 45]
    }]
  },
  // Configuration options go here
  options: {}
});

var chart_2_node = document.getElementById('chart_2');
new Chart(chart_2, {
  // The type of chart we want to create
  type: 'bar',
  responsive: true,
  // The data for our dataset
  data: {
    labels: ['April', 'May', 'June'],
    datasets: [{
      label: 'My Second dataset',
      backgroundColor: 'rgb(22, 22, 22)',
      borderColor: 'rgb(22, 22, 22)',
      data: [0, 10, 5]
    }]
  },
  // Configuration options go here
  options: {}
});

Chart.helpers.each(Chart.instances, function(instance){
  if (instance.chart.canvas.id === "chart_1") {
    console.log("id:"  + instance.chart.canvas.id +" | February before update: " + instance.chart.data.datasets[0].data[1]);
    instance.data.datasets[0].data[1] = 50; // Would update the second dataset's value of 'February' to be 50
    instance.update(); // Calling update now animates the position of February from 30 to 50.
  }
  if (instance.chart.canvas.id === "chart_2") {
     /* do something */
  }
})
<section>
  <h4>chart 1</h4>
  <canvas id="chart_1"></canvas></section>
<section>
  <h4>chart 2</h4>
  <canvas id="chart_2"></canvas>
</section>


<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
© www.soinside.com 2019 - 2024. All rights reserved.