我正在尝试在网页上显示动态数量的图表。图表的数量将根据“守护程序服务”的数量而变化。我为每个画布创建画布。但是,当我尝试绘制图表时,仅最后一个渲染。所有画布均已写入文档,但为空白。
这是我的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>
任何帮助将不胜感激。谢谢。
答案 0 :(得分:1)
我的建议是按如下所示以编程方式创建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。