每秒刷新一次图表数据javascript

refresh chart data every second javascript(每秒刷新一次图表数据javascript)
本文介绍了每秒刷新一次图表数据javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个带有图表的 html 网页,该图表显示电压水平不断变化.我想每秒刷新一次页面,以便条形图中的条形变为新值.我不确定如何像这样更新图表数据.到目前为止,我有以下内容:

I am creating an html web page with a chart on that shows voltage levels continuously changing. I want to refresh the page every second so that the bars in the bar chart go to the new values. I am not sure how to update the chart data like this. I have the following so far:

Chart.plugins.unregister(ChartDataLabels);

function myFunction() {
  var cells = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
  var voltages = [];
  for (i = 0; i < 16; i++) {
    voltages[i] = Math.floor(28 + Math.floor(Math.random() * 8)) / 10;
  }

  var colours = [];
  for (i = 0; i < voltages.length; i++) {
    colours[i] = getColour(voltages[i]);
  }

  var ctx = document.getElementById("voltageChart");
  var voltageChart = new Chart(ctx, {
    plugins: [ChartDataLabels],
    type: "bar",
    data: {
      labels: cells,
      datasets: [{
        data: voltages,
        backgroundColor: colours,
      }]
    },
  });

  function updateData(chart) {
    chart.data.datasets[0].data = voltages;
    chart.data.datasets[0].backgroundColor = colours;
    chart.update();
  }

  function refreshData() {
    for (i = 0; i < 16; i++) {
      voltages[i] = Math.floor(28 + Math.floor(Math.random() * 8)) / 10;
    }

    for (i = 0; i < voltages.length; i++) {
      colours[i] = getColour(voltages[i]);
    }

    updateData(voltageChart);
  }

  setInterval(refreshData, 1500);
}

推荐答案

我们可以使用 chart.data.datasets.pop() 推送新数据 chart.data.datasets.push() 然后调用 chart.js 函数 chart.update 重新渲染图形.这是示例:https://codepen.io/bhupendra1011/pen/MWwWogO?editors=1111.

We can use chart.data.datasets.pop() and push new data chart.data.datasets.push() and then invoke chart.js function chart.update to re-render the graph . here is the example : https://codepen.io/bhupendra1011/pen/MWwWogO?editors=1111.

更多关于添加/删除数据这里

More on adding/removing data here

这篇关于每秒刷新一次图表数据javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)