You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ChartJS更新图表保留旧数据叠加新数据问题求助

ChartJS图表更新数据叠加问题求助

我已经花了好几天解决ChartJS的图表更新问题,一直毫无头绪。程序提供输入控件让用户选择要图表化的数据,搭配触发图表生成的按钮。首次生成的图表正常,但用户修改数据后再次、多次点击按钮时,之前图表的所有数据会保留并叠加最新选择的数据。

这种表现完全符合chart.destroy()未生效的情况,或是使用const创建图表对象导致无法删除初始数据的情况。

已尝试的环境组合

  • 浏览器:Chrome 107.0.5304.121、Microsoft Edge 107.0.1418.56、Firefox 107.0
  • Chart.js版本:3.9.1、3.6.2、3.7.0
  • jQuery版本:v3.6.1、v1.11.1

其他无效尝试

  • 使用"use strict"模式
  • 销毁图表对象的同时移除并重新添加包含canvas的div
  • 销毁图表后用setTimeout延迟更新图表

相关代码

<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/chart.js"></script>
<script type="text/javascript" src="js/dropdownLists.js"></script>
<script type="text/javascript" src="js/chartDataFunctions.js"></script>
<script type="text/javascript" src="js/chartJSFunctions.js"></script>

<body>
<div class="metadatasetup4" id="buttons">
    <button class="download" id="getchart" value="Get Chart">Chart</button>
    <button class="download" id="downloadchart" value="Download">Download</button>
</div>

<div id="bigchartdiv" class="bigchart">
  <canvas id="myChart"></canvas>
</div>
</body> 

<script>
$(window).on('load',function(){
//NOTE 1: In of my attempts to troubleshoot I tried strict mode (it didn't work)
//"use strict"; 
let data = {
    labels: lbl,
        datasets: [
        ]
};
let config = {
    type: 'line',
    data: data,
    options: {
        scales: {
          y: {
            type: 'linear',
            display: true,
            position: 'left',
            min:0,
            pointStyle:'circle',
          },
          y1: {
            type: 'linear',
            display: true,
            position: 'right',
            suggestedMax: 25,
            min: 0,
            pointStyle: 'cross',

            // grid line settings
            grid: {
              drawOnChartArea: false, // only want the grid lines for one axis to show up
            },
          },
        }                       
    }
};

// NOTE 2: The next line below, beginning with "var bigChartHTML =" was one of my later attempts to 
// solve the problem.  It didn't work, but my thought process was that if I removed 
// the div containing the canvas, AND destroyed the chart object, that appending a "fresh" 
// chart div to the body might be a work-around.  This did not work. 
var bigChartHTML = '<div id="bigchartdiv" class="bigchart"><canvas id="myChart"></canvas></div>'


let ctx = document.getElementById('myChart').getContext('2d');
let bigChart = null; 

// The getChartData() function below uses Ajax to populate various dropdown lists
// which enable the user to select the data is to be charted.  
// There are no chartjs-related operations in getChartData() 
getChartData();


$('#buttons').on('click','#getchart',function(){
    if (bigChart!=null) {
        
        //removeData(bigChart);
        bigChart.destroy();
        //bigChart = 1;

    }
    $("#bigchartdiv").empty();   //for this and next 2 lines, see NOTE 2 above
    $("#bigchartdiv").remove();  
    $(bigChartHTML).insertAfter("#chartcontrols");
    bigChart = new Chart(document.getElementById('myChart'),config);
    //NOTE 3: I thought maybe bigChart.destroy() took time, so I tried 
    //        using the setTimeout function to delay updating the chart
    //        (didn't work, but I left it in the code, anyway.)
    setTimeout(function() {updateChart(bigChart)}, 2000);
    //updateChart(bigChart);            
}); 


    // NOTE: The updateChart() function is actually included in "js/chartDataFunctions.js" 
    function updateChart(chart) {
            /*
            This section of the program reads the HTML elements then uses them
            to make an Ajax request to sql server, and these become the
            parameters for the newDataSet() function below.
            */
            
            newDataset(chart,firstElement,newdataset,backgroundcolor,color);        
    }
    
    // NOTE: The newDataSet() function is actually included in "js/chartJSFunctions.js" 
    // I show it here for brevity.   
    // It decides which axis (y or y1) to use to plot the datasets
    // the dataset is pushed into the data, and chart.update() puts it in the chart object
    function newDataset(chart,label,data,bgcolor='white',color='rgb(255,255,255)') {
        var maxValue = Math.max(...data);
        if (Number.isNaN(maxValue)) {
            return; 
        }
        if (maxValue == 0) {
            return;
        }
        var axisID = 'y';
        var ptStyle = 'circle';
        //var pStyle = 'circle';
        if (maxValue < 50) {
            axisID = 'y1';
            bgcolor = 'white';
            //ptStyle = 'Star'
        }
        chart.data.datasets.push({
            label:label,
            yAxisID:axisID,
            data:data,
            borderColor:color,
            backgroundColor:bgcolor,
            //pointStyle:ptStyle
        });
        chart.update();
    }

});


</script>

内容的提问来源于stack exchange,提问作者elliott954

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 02:10:17