gpt4 book ai didi

javascript - 为chart.js动态添加 Canvas

转载 作者:行者123 更新时间:2023-12-03 00:04:46 24 4
gpt4 key购买 nike

我正在尝试在网页上显示动态数量的图表。图表的数量将根据“守护进程服务”的数量而变化。我为每个人创建 Canvas 。但是,当我尝试绘制图表时,仅显示最后一个图表。所有 Canvas 均写入文档,但为空白。

这是我的 JavaScript:

var specContainer = document.getElementById("SpecificContainer");
daemonCanvases = [];
daemonCharts = [];
for (var i=0;i<data.services.length;i++) {
specContainer.innerHTML += '<div><canvas id="' + data.services[i] + '"></canvas></div>';
var daemonCanv = document.getElementById(data.services[i]).getContext('2d');

daemonCanvases.push(daemonCanv);

daemonCharts.push(new Chart(daemonCanvases[i], {
type: 'line',
data: {
labels: timeSpanLabels,
datasets: myDataSets,
},
options: {
responsive: false,
}
}));
}

和 HTML:

<body>
<div id="display">
<div id="SpecificContainer">
</div>
</div>
</body>

如有任何帮助,我们将不胜感激。谢谢。

最佳答案

我的建议是以编程方式创建 Canvas 节点,如下所示并附加。

var canvas = document.createElement("canvas");
canvas.id = "my-id";
specContainerNode.appendChild(canvas);

// ----- more code ------

setTimeout(function() {
/* TIP: This timeout will be helpful to execute logic after a repaint.
Thus, this block will execute only after nodes were attached */

// ----- more code -----

}, 0);

查看此Q&A了解更多信息。

关于javascript - 为chart.js动态添加 Canvas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55012536/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com