最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to make chart js display values ​in real time? - Stack Overflow

programmeradmin5浏览0评论

I just learned to make a web And I want to know how to make chart js to display values ​​in real time. Can you guys advise or tell me how to do it for me?

var data = [];
var temp = [];

async function getRandomUser() {
    const response = await fetch('http://localhost:1111/chartpie');
    const data = await response.json();
    addData(data);
}

function addData(object) {
    temp.push(object.temperature);
    var z = 80;
    var y = z - temp;
    var ctx = document.getElementById("myPieChart");
    myPieChart = new Chart(ctx, {
        type: "doughnut",
        data: {
            labels: ["Temperature", "Null"],
            datasets: [{
                data: [temp, y],
                backgroundColor: [
                    "orange",
                    "rgba(0, 172, 105, 1)"
                ],
            }]
        },
        options: {
            legend: {
                display: false
            },
        }
    });
}

getRandomUser()

The values ​​I retrieved are the values ​​retrieved from mongoDB, fetched in the form of an array. Thank You!

I just learned to make a web And I want to know how to make chart js to display values ​​in real time. Can you guys advise or tell me how to do it for me?

var data = [];
var temp = [];

async function getRandomUser() {
    const response = await fetch('http://localhost:1111/chartpie');
    const data = await response.json();
    addData(data);
}

function addData(object) {
    temp.push(object.temperature);
    var z = 80;
    var y = z - temp;
    var ctx = document.getElementById("myPieChart");
    myPieChart = new Chart(ctx, {
        type: "doughnut",
        data: {
            labels: ["Temperature", "Null"],
            datasets: [{
                data: [temp, y],
                backgroundColor: [
                    "orange",
                    "rgba(0, 172, 105, 1)"
                ],
            }]
        },
        options: {
            legend: {
                display: false
            },
        }
    });
}

getRandomUser()

The values ​​I retrieved are the values ​​retrieved from mongoDB, fetched in the form of an array. Thank You!

Share Improve this question asked Nov 1, 2022 at 18:58 thawatthawat 431 gold badge1 silver badge5 bronze badges 2
  • 1 If you want to update it in real time with you current code, then you mean polling. Which is basically connecting to server after (N) seconds and update data with new response. You can achieve that by setting timeOut around getRandomUser() – A. Khaled Commented Nov 1, 2022 at 21:13
  • The best solution could be through websocket. You need to handle that by backend first. Websocket is a protocol (ws://) which is been established between client and server. It enables client to listen to any change happens on server side on specific channel. It could be for specific time or forever. – A. Khaled Commented Nov 1, 2022 at 21:16
Add a ment  | 

1 Answer 1

Reset to default 4

You can just update the chart in "real time" by adding to the charts data array.

see: https://www.chartjs/docs/latest/developers/updates.html

Adding and removing data is supported by changing the data array. To add data, just add data into the data array as seen in this example.

function addData(chart, label, data) {
    chart.data.labels.push(label);
    chart.data.datasets.forEach((dataset) => {
        dataset.data.push(data);
    });
    chart.update();
}

For example...

const canvas = document.getElementById('myChart');
canvas.height = 75;

const labels = [
  'dju32',
  'ad6b2',
  '0f23f',
  'asd4c',
];

const data = {
  labels: labels,
  datasets: [{
    label: 'Test',
    backgroundColor: 'rgb(255, 99, 132)',
    borderColor: 'rgb(255, 99, 132)',
    data: [0, 10, 5, 4],
  }]
};

const config = {
  type: 'line',
  data: data,
  options: {}
};

const myChart = new Chart(
  canvas,
  config
);

// function to update the chart 
function addData(chart, label, data) {
  chart.data.labels.push(label);
  chart.data.datasets.forEach((dataset) => {
    dataset.data.push(data);
  });
  chart.update();
}

// randomly add new data
setInterval(function() {
  const newLabel = (Math.random() + 1).toString(36).substring(7);
  const newData = Math.floor(Math.random() * 10);
  addData(myChart, newLabel, newData);
}, 1000);
<script src="https://cdn.jsdelivr/npm/chart.js"></script>
<div>
  <canvas id="myChart"></canvas>
</div>

发布评论

评论列表(0)

  1. 暂无评论