Chart.js:图表类型的动态变化(以Line to Bar为例)

2022-01-22 00:00:00 vue.js chart.js

我正在尝试根据选择框更改热交换图表类型.如果数据需要更新,它就会改变.

I am trying to hot swap chart types based on select box changes. If data needs to be updated, it changes.

例如,在页面加载时,我会创建一个这样的图表:

So for example, on page load I create a chart like this:

var config = {
     type: 'line',
     data: {
        labels: this.labels,
        datasets: [{
            label: 'Some Label',
            data: this.values
        }]
     },
     options: {
         responsive: true
     }
}
var context = document.getElementById('canvas').getContext('2d');
window.mychart = new Chart(context, config);

然后我将组合框更改为条形图.我在页面加载时使用条形图测试了数据,效果很好.

But then I change the combo box to a bar chart. I have tested the data with bar chart on page load, and it worked great.

这是我尝试更改图表的方式.

Here's how I am trying to change the chart.

window.mychart.destroy();

// chartType = 'bar'
config.type = chartType;

var context = document.getElementById('canvas').getContext('2d');
window.mychart = new Chart(context, config);

window.mychart.update();
window.mychart.render();

但是什么也没发生.折线图仍然存在.如何动态更改图表类型?(即使这意味着破坏和重新创建图表画布).

But nothing happens. The line chart remains. How can I dynamically change the chart type? (Even if it means destroying & re-creating the chart canvas).

更新

注意它看起来实际上是在破坏图表,但不断重绘折线图,即使我这样做 console.log(config.type); 并且它返回 bar,而不是 line

Note it looks like it is actually destroying the chart, but keeps redrawing a line chart, even though I do console.log(config.type); and it returns bar, not line

推荐答案

修复

  • 销毁旧图表(以移除事件侦听器并清除画布)
  • 制作配置对象的深层副本
  • 更改副本的类型
  • 传递副本而不是原始对象.
  • 这是一个有效的 jsfiddle 示例

    示例概述:

    var temp = jQuery.extend(true, {}, config);
    temp.type = 'bar'; // The new chart type
    myChart = new Chart(ctx, temp);
    

    注意:使用 Chart.js 的 2.0.1 版

    NOTE: Using version 2.0.1 of Chart.js

    Chart.js 会修改您传入的配置对象.因此,您不能只更改config.type".您可以进入修改后的对象并将所有内容更改为您想要的类型,但保存原始配置对象要容易得多.

    Chart.js modifies the config object you pass in. Because of that you can not just change 'config.type'. You could go into the modified object and change everything to the type you want, but it is much easier to just save the original config object.

相关文章