如何使用Chart.js在一个页面中拥有多个图表



我试图在同一页面上用Chart.js绘制两个以上的图表,并在循环中创建了一个动态div,其中包含图表的所有数据,如下所示:

<div class="col-4">
<canvas class="trend-chart" id="chart{{ p.sNo }}" width="500" height="100" role="img" data-pv="{{ p.recentPageViews }}">
</canvas>
</div>

基于class名称动态创建图表的JavaScript代码:

const labels = [
'22-12-12',
'22-12-13',
'22-12-14',
'22-12-15',
'22-12-16',
'22-12-17',
'22-12-18',
'22-12-19',
'22-12-20',
'22-12-21'
];
const config = {
type: 'line',
animation: true,
options: {}
};
var charts = document.getElementsByClassName("trend-chart");
for (var i = 0; i < charts.length; i++) {
pv = charts[i].getAttribute('data-pv');
id = charts[i].getAttribute('id');
window['config' + id] = config;
window['data' + id] = {
labels: labels,
datasets: [{
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: JSON.parse(pv),
}]
};
window['config' + id]['data'] = window['data' + id];
window['ctx' + id] = document.getElementById(id).getContext('2d');
window['myChart' + id] = new Chart(
window['ctx' + id],
window['config' + id]
);
}

除了鼠标悬停到图表数据点时的工具提示外,其他一切都很好。我没有看到工具提示,我得到以下错误:

Uncaught TypeError: Cannot read properties of null (reading 'getLabelAndValue')
at Eo (chart.js:13)
at Ho._createItems (chart.js:13)
at Ho.update (chart.js:13)
at Ho.handleEvent (chart.js:13)
at Object.afterEvent (chart.js:13)
at Q (chart.js:13)
at Vs._notify (chart.js:13)
at Vs.notify (chart.js:13)
at hn.notifyPlugins (chart.js:13)
at hn._eventHandler (chart.js:13)*

请按照下面的代码在数据集中添加标签属性。

datasets: [{
label: 'Some text',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: JSON.parse(pv),
}]

嗨,想办法解决它,主要问题是上下文设置不正确,所以我喜欢下面的内容来克服

window.addEventListener('load', function() {
var charts = document.getElementsByClassName("trend-chart");
for (var i = 0; i < charts.length; i++) {
pv = charts[i].getAttribute('data-pv');
id = charts[i].getAttribute('id');
new Chart(
document.getElementById(id).getContext('2d'), {
type: 'line',
animation: true,
data: {
labels: JSON.parse(charts[i].getAttribute('data-pvd')),
datasets: [{
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: JSON.parse(pv),
}]
},
options: {plugins: {......},scales: {......}}
}
);
}

});

相关内容

  • 没有找到相关文章

最新更新