[英]chart.js v2 update chart without global variable
I am using chart.js v2.5.0. 我正在使用chart.js v2.5.0。
I want to create charts dynamically without using a global variable. 我想动态创建图表而不使用全局变量。
For example, I want to use code similar to this: https://jsfiddle.net/DUKEiLL/sf57xw6b/ 例如,我想使用类似于以下的代码: https : //jsfiddle.net/DUKEiLL/sf57xw6b/
function UpdateChart(ctrl) {
var config = $("#" + ctrl).data("ChartJs");
config.data.datasets.forEach(function (dataset) {
dataset.data = dataset.data.map(function () {
return randomScalingFactor();
});
});
var ctx = document.getElementById(ctrl).getContext("2d");
var TempMyDoughnut = new Chart(ctx, config);
TempMyDoughnut.update();
}
But it doesn't work properly: when the user presses "update" button and hovers over the chart, previous instance are suddenly displayed. 但是它不能正常工作:当用户按下“更新”按钮并将鼠标悬停在图表上时,会突然显示以前的实例。
Since you are creating a new chart on each execution of UpdateChart
function, hence you would have to destroy any previous instance of chart to prevent the hover issue. 由于您将在每次执行
UpdateChart
函数时创建一个新图表,因此,您必须销毁图表的任何先前实例,以防止发生悬停问题。
To accomplish so, you could simply replace your UpdateChart
function with the following ... 为此,您可以简单地用以下代码替换
UpdateChart
函数:
function UpdateChart(ctrl) {
var config = $("#" + ctrl).data("ChartJs");
config.data.datasets.forEach(function(dataset) {
dataset.data = dataset.data.map(function() {
return randomScalingFactor();
});
});
// destroy previous instance of chart
var meta = config.data.datasets[0]._meta;
for (let i in meta) {
if (meta[i].controller) meta[i].controller.chart.destroy();
}
var ctx = document.getElementById(ctrl).getContext("2d");
var TempMyDoughnut = new Chart(ctx, config);
}
Here is the working example on jsFiddle 这是jsFiddle上的工作示例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.