【问题标题】:Javascript ChartJS updating chart and canvas permanentlyJavascript ChartJS 永久更新图表和画布
【发布时间】:2017-01-22 19:51:00
【问题描述】:

我在 chartJS 中制作了一个图表,我想根据用户从下拉列表中选择的内容,使用相同的画布使用新数据对其进行更新。问题是当我执行更新功能时,图表会使用新数据更新,但一段时间后它会一直回到原始图表。我该如何解决这个问题?这是代码,感谢您的帮助:

/* Original Chart */
var ctx3 = document.getElementById("canvas3").getContext("2d");

var canvas3 = new Chart(ctx3, {
    type: 'line',
    data: {
        labels: stationRentalsLabels,
        datasets: [{
            label: 'Wypożyczenia',
            fillColor: "rgba(220,280,220,0.5)",
            strokeColor: "rgba(220,220,220,1)",
            backgroundColor: "rgba(153,255,51,0.4)",
            data: stationRentalsData
        }]
    }
});

/* event listener on drop-down list, when triggered, update chart */
select.addEventListener('change', function() {
    updateChart()
});

/* Update Chart */
function updateChart() {
    var stationRentalsHoursTemp = [];
    var stationRentalName = [];

    var determineHour = selectNumber.options[selectNumber.selectedIndex].innerHTML;
    for (var i = 0; i < stationRentalsHours.length; i++) {
        if (determineHour == stationRentalsHours[i]) {
            stationRentalsHoursTemp.push(stationRentalsData[i])
            stationRentalName.push(stationRentalsLabels[i]);
        }
    }

    /* Updated Chart */
    var ctx3 = document.getElementById("canvas3").getContext("2d");
    var canvas3 = new Chart(ctx3, {
        type: 'line',
        data: {
            labels: stationRentalName,
            datasets: [{
                label: 'Wypożyczenia',
                fillColor: "rgba(220,280,220,0.5)",
                strokeColor: "rgba(220,220,220,1)",
                backgroundColor: "rgba(153,255,51,0.4)",
                data: stationRentalsHoursTemp
            }]
        }
    });
}

【问题讨论】:

    标签: javascript canvas charts


    【解决方案1】:

    您正在与以前一样在同一 div 中的更新函数上创建新图表,但为了做到这一点,您需要在调用 updateChart 函数之前调用destroy 函数来销毁图表的前一个实例。

    canvas3.destroy();

    解决问题的另一种方法是通过调用更新函数调用 updateChart 函数时替换数据而不是图表本身(不初始化新图表)

    function updateChart() {
        var stationRentalsHoursTemp = [];
        var stationRentalName = [];
    
        var determineHour = selectNumber.options[selectNumber.selectedIndex].innerHTML;
        for (var i = 0; i < stationRentalsHours.length; i++) {
            if (determineHour == stationRentalsHours[i]) {
                stationRentalsHoursTemp.push(stationRentalsData[i])
                stationRentalName.push(stationRentalsLabels[i]);
            }
        }
        // just update the label and dataset not the entire chart
        canvas3.data.labels = stationRentalName;
        canvas3.data.datasets[0].data = stationRentalsHoursTemp;
        canvas3.update();
    
    }
    

    【讨论】:

      猜你喜欢
      • 2018-01-08
      • 2020-12-14
      • 2019-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      相关资源
      最近更新 更多