请帮忙,
我需要使用ajax在canvasjs中切换图形。我的数据点来自json格式。例如,折线图 - 饼图 - 条形图反之亦然。
非常感谢你的帮助。告诉我该怎么做。
答案 0 :(得分:0)
CanvasJS支持图表选项的动态更新。请看下面的示例,该示例显示了从json渲染多系列图表并根据下拉值更改图表类型。
var dps1 = [], dps2 = [];
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "MultiSeries Chart from JSON"
},
animationEnabled: true,
toolTip: {
shared: true
},
data: [
{
type: "spline",
dataPoints: dps1
},
{
type: "spline",
dataPoints: dps2
}
]
});
$.when(
$.getJSON("https://api.myjson.com/bins/zb96f", function(data) {
for(var i = 0; i < data.length; i++) {
dps1.push({ label: data[i].label, y: data[i].y1 });
dps2.push({ label: data[i].label, y: data[i].y2 });
}
})
).then(function() {
chart.render();
});
var chartType = document.getElementById('chartType');
chartType.addEventListener( "change", function(){
for(var i = 0; i < chart.options.data.length; i++){
chart.options.data[i].type = chartType.options[chartType.selectedIndex].value;
}
chart.render();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<br/><!-- Just so that JSFiddle's Result label doesn't overlap the Chart -->
<div>Chart Type:
<select id="chartType" name="Chart Type">
<option value="line">Line</option>
<option value="column">Column</option>
<option value="bar">Bar</option>
<option value="stackedColumn">Stacked Column</option>
<option value="stackedBar">Stacked Bar</option>
</select>
</div>
<div id="chartContainer" style="height: 260px; width: 100%;"></div>