我正在尝试加载新数据(隐藏特定图表),我尝试了destroy()
函数like here但它无法正常工作,我确实不知道自己错过了什么
我想加载一个数据(两个),但我想选择哪一个可见。
HTML
<canvas id="linechart"></canvas>
<div>
<a id="current">Current</a>
<a id="forecast">Forecast</a>
</div>
的JavaScript
$(document).ready(function(){
var canvas = document.getElementById('linechart');
var ctx = canvas.getContext('2d');
var current = [800, 1350, 1400, 1600, 2600, 3100];
var forecast = [400, 1050, 1200, 1300, 1800, 2400];
var data = {
labels: ["2", "4", "8", "12", "16", "20"],
pointDotRadius: 0,
pointRadius: 0,
pointBorderWidth : 0,
pointHitRadius: 0,
datasets: [
{
label: "current",
fillColor: "rgba(220,220,220,0)",
strokeColor: "#7bc775",
pointColor: "#7bc775",
data: current,
},
{
label: "forecast",
fillColor: "rgba(151,187,205,0)",
strokeColor: "#fed477",
pointColor: "#fed477",
data: forecast,
}]
};
var myLineChart = new Chart(ctx, {
type: 'line',
data: data
});
var step = 800;
var max = 3200;
var start = 0;
window.myObjBar = new Chart(ctx).Line(data, {
scaleOverride: true,
scaleSteps: Math.ceil((max-start)/step),
scaleStepWidth: step,
scaleStartValue: start,
responsive : true
});
$('#current').click(function(){
current = [];
if(myLineChart!== null){
myLineChart.destroy();
myLineChart = new Chart(ctx, {
type: 'line',
data: data
});
}
});
});
答案 0 :(得分:1)
我使用最新版本的Charts.js
找到了问题的解决方案使用销毁并将数据存储在数组中。单击控件时,它会销毁图表并使用所选数据重建新图表
var mychart = new Chart(ctx,config);
$('.selector').click(function(){
data.datasets = [datasets[$(this).data('index')]];
if(mychart!== null){
mychart.destroy();
mychart = new Chart(ctx, config);
}
});
请在此处查看更新的小提琴:https://jsfiddle.net/3563ko2t/6/