我试图根据选择框更改热交换图表类型.如果需要更新数据,则会更改.
因此,例如,在页面加载时,我创建一个这样的图表:
var config = {
type: 'line',
data: {
labels: this.labels,
datasets: [{
label: 'Some Label',
data: this.values
}]
},
options: {
responsive: true
}
}
var context = document.getElementById('canvas').getContext('2d');
window.mychart = new Chart(context, config);
Run Code Online (Sandbox Code Playgroud)
但后来我将组合框更改为条形图.我在页面加载时用条形图测试了数据,效果很好.
这是我试图改变图表的方式.
window.mychart.destroy();
// chartType = 'bar'
config.type = chartType;
var context = document.getElementById('canvas').getContext('2d');
window.mychart = new Chart(context, config);
window.mychart.update();
window.mychart.render();
Run Code Online (Sandbox Code Playgroud)
但没有任何反应.折线图仍然存在.如何动态更改图表类型?(即使这意味着破坏并重新创建图表画布).
UPDATE
注意它看起来实际上正在破坏图表,但是不断重新绘制折线图,即使我这样做console.log(config.type);并且它返回bar,而不是line
L B*_*ahr 15
示例概述:
var temp = jQuery.extend(true, {}, config);
temp.type = 'bar'; // The new chart type
myChart = new Chart(ctx, temp);
Run Code Online (Sandbox Code Playgroud)
注意:使用Chart.js的2.0.1版
Chart.js修改你传入的配置对象.因此你不能只改变'config.type'.您可以进入修改后的对象并将所有内容更改为所需的类型,但只保存原始配置对象要容易得多.
只是为了跟进这现在已在 v.2.1.3 中修复,随后是/sf/users/16756281/
document.getElementById('changeToLine').onclick = function() {
myChart.destroy();
myChart = new Chart(ctx, {
type: 'line',
data: chartData
});
};
Run Code Online (Sandbox Code Playgroud)
确认已在最新版本中修复。查看http://codepen.io/anon/pen/ezJGPB并按图表下方的按钮将其从条形图更改为折线图。
在 Chart.js 3.8.0 中你可以这样做:
let chart = new Chart(ctx, {
type: "line",
data: {
// ...
},
options: {
// ...
}
});
chart.config.type = "bar";
chart.update();
Run Code Online (Sandbox Code Playgroud)
您还可以通过这种方式更改数据和选项
有关更新的 Chart.js 文档: https://www.chartjs.org/docs/latest/developers/updates.html
代码笔示例:https ://codepen.io/3zbumban/pen/yLKMMJx
| 归档时间: |
|
| 查看次数: |
14549 次 |
| 最近记录: |