Chart.js: Dynamic Changing of Chart Type (Line to Bar as Example)

后端 未结 3 1439
独厮守ぢ
独厮守ぢ 2020-12-17 19:53

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:

3条回答
  •  旧巷少年郎
    2020-12-17 20:20

    The Fix

    • Destroy the old chart (to remove event listeners and clear the canvas)
    • Make a deep copy of the config object
    • Change the type of the copy
    • Pass the copy instead of the original object.

    Here is a working jsfiddle example

    Example Overview:

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

    NOTE: Using version 2.0.1 of Chart.js

    Why this works

    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.

提交回复
热议问题