如何将数据从数据库添加到 chartjs-plugin-streaming

how to add data from database to chartjs-plugin-streaming

你好,我正在制作一个图表,其中将显示一段时间内的温度,我需要实时进行,我找到了 chart.js 但我不知道如何添加从数据库到图形的数据。

var ctx = document.getElementById("lineChart2").getContext("2d");
const labels = {{ time | safe }};
const values = {{ temp | safe }};

var lineChart = new Chart(ctx, {
    type: "line",
    data: {
        labels: labels,
        datasets: [
            {
                label: "Temperatura °C",
                data: [values],
                fill: false,
                borderColor: "#28a745",
                lineTension: 0.1
            }
        ]
    },
    options: {
        scales: {
            x: {
                type: 'realtime',
                realtime: {
                    onRefresh: chart => {
                        chart.data.datasets.forEach(dataset => {
                            dataset.data.push({
                                x: //IT'S HERE labels
                                y: //IT'S HERE values
                            });
                        });
                    }
                }
            }
        },
        
    }
});

const labels = [1637903351687, 1637903353675, 1637903355678, 1637903357678, 1637903359674, 1637903361679, 1637903363672, 1637903365668, 1637903367686, 1637903369669, 163790337167] //time unix

const values = [24, 24, 5, 10, 1, 30, 1] //temperature

根据 Chart.js documentation 你可以用这样的东西更新你的图表:

async function updateGraphWithData() {
    const data = await apiCall(); // Your call to your backend

    lineChart.data.datasets.forEach(dataset => {
        dataset.data = data;
    });

    lineChart.update();
}

您需要能够触发该功能的东西(例如单击按钮)或其他东西。