javascript - 带有 try catch 的 ChartJs
问题描述
所以我正在尝试制作一个 JS 函数,该函数使用ChartJS
的变量/数据是一个 JSON 对象。我之所以使用 try/catch 是因为这里下面的两行:
let labels = json_data.data.map(e => e.StartTime);
let data = json_data.data.map(e => e.StatusId);
如果设置了任何数据,则并不总是设置,但如果没有设置,则只有一组
let data = json_data.message.map(e => e.message);
除非在页面加载时,否则没有设置任何内容。
更改下拉列表时 JSON 对象<Select>
会更改,如果其中有数据canvas
则加载,但如果用户随后选择没有数据的对象,我希望移植为空/销毁,但我不能这样做,因为我'm 在 try catch 中,如果我也在 catch 中定义了它,那么它说 ID 已经在使用中。我该怎么做才能“重置/销毁”它?
function chartJSLoad(json_data) {
try {
let labels = json_data.data.map(e => e.StartTime);
let data = json_data.data.map(e => e.StatusId);
console.log(labels);
console.log(data);
var ctx = document.getElementById('canvaschartjs').getContext('2d');
var myChart = new Chart(ctx, {
data: {
datasets: [{
type: 'bar',
label: 'Bar Dataset',
data: data,
backgroundColor: 'rgba(0, 150, 90)',
borderColor: 'rgba(0, 255, 90)',
order: 2
}, {
type: 'line',
label: 'Line Dataset',
data: data,
backgroundColor: 'rgba(150, 0, 90)',
borderColor: 'rgba(255, 0, 90)',
order: 1
}],
labels: labels
},
options: {
maintainAspectRatio: false,
responsive: true,
scales: {
x: {
stacked: true,
},
y: {
stacked: true
}
}
}
});
} catch (error) {
if (typeof json_data !== 'undefined') {
myChart.destroy();
alert(json_data.message);
}
}
}
解决方案
您可以使用静态方法getChart
检查具有该上下文的图表是否已经存在,如果存在,您可以获得可以销毁的图表实例:
catch (error) {
if (typeof json_data !== 'undefined') {
let chart = Chart.getChart('canvaschartjs');
if (typeof chart !== 'undefined') {
chart.destroy()
}
alert(json_data.message);
}
}
现场示例:
var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderColor: 'pink'
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderColor: 'orange'
}
]
},
options: {}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
let myChart = new Chart(ctx, options);
let chart = Chart.getChart('chartJSContainer');
if (typeof chart !== 'undefined') {
chart.destroy() // Does not show anything because of this line, comment it out to show again
}
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.js"></script>
</body>
推荐阅读
- kotlin - Retrofit2 对查询值进行编码,即使编码=true
- php - Yii2 在使用模型渲染视图时显示空白页
- php - PHP 向特定页面上的每个用户推送重新加载
- android - 尝试同步自定义 rom 存储库集时出现存储库同步问题
- c++ - 如何在基于范围的 for 循环中进行初始化
- html - 我试图让每个网络浏览器的样式看起来都一样
- firebase - 使用没有组织或文件夹的服务帐户创建 GCP 和 Firebase 项目
- javascript - 有没有办法以类似于将变量添加到窗口对象的方式将变量添加到范围?
- java - 自定义 Spinner 项目中的可点击按钮阻止点击项目本身
- extjs - Rhino Parse Error (missing ] after element list