为chart.js动态添加画布

问题描述 投票:0回答:1

我试图在网页上显示动态数量的图表。图表的数量将根据“守护程序服务”的数量而有所不同。我为每个人创建了画布。但是当我尝试绘制图表时,只有最后一个渲染。所有画布都写入文档但是空白。

这是我的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>

任何帮助,将不胜感激。谢谢。

javascript canvas chart.js
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.