【问题标题】:Realtime chart JS in Java obtaining the data from a sensor ;Chart.js: Failed to create chart: can't acquire context from the given itemJava中的实时图表JS从传感器获取数据; Chart.js:无法创建图表:无法从给定项目获取上下文
【发布时间】:2020-07-10 15:34:40
【问题描述】:

我正在尝试使用 chart.js 绘制实时图表。传感器提供实时数据,这些数据被更新以绘制在图表上。我已按照文档中提供的步骤添加或更新数据,但它向我显示错误:Chart.js:无法创建图表:无法从给定项目获取上下文check image please 我正在使用构造函数实现一个新类(makeChart),其中图表对象和图表实例在构造函数中定义。接下来是同一类中的 addData 方法,该方法在刷新类(另一个名为 Dashbaord 的类)中调用。 AddData 方法假设以文档中给出的相同格式更新数据。这都在一个名为dashboard.js 的java文件中。要绘制图表的画布位于名为 dashbaord.html 的单独 HTML 文件中。

控制台显示 ctx 和 canvas 等于 null。

当 (this.testChart.update();) 被取消注释时,错误显示在四个不同的行:

1- this.makeChart = new makeChart;

2- that.makeChart.addData(result.particles.PM0_3); // 刷新时

3- this.testChart = new Chart (ctx,{ // 在图表实例中

4- this.testChart.update(); // chart.js提供的更新方式

评论 this.testChart.update();在 this.makeChart = new makeChart;this.testChart = new Chart (ctx,{ 处出现错误,这是未绘制图表的主要原因。 p>

我怀疑该错误与两个类之间的连接有关,因为当我尝试在第一个类中绘制图表时,它可以工作,但没有来自传感器的实时数据和更新时间。我将在下面发布 java 代码以及dashboard.html 行来绘制图表。

期待你们的帮助,很抱歉在这里发了这么长的帖子。我很感激...

dashboard.js 代码:

class Dashboard {
   constructor(jsonRPC, auth){

    this.jsonRPC = jsonRPC;
    this.auth = auth;
    this.updateInterval = 10;                //every 10 seconds
    this.makeChart = new makeChart;

}

run() {

    var that = this;
    that.jsonRPC.call('extension.get', {'select':'data'}).then(function (result) {

    //Initialize Device Infos
    $('#tab_info').load('html/dashboard.html #content', function(){
    $(".GaugeMeter").gaugeMeter();// Initialize GaugeMeter plugin

        //Start Data Refresh Cycle
        that.refresh();
    });
  });
}

refresh() { 
    var that = this;
    that.jsonRPC.call('extension.get', {'select':'data'}).then(function (result) {
    that.makeChart.addData(result.particles.PM0_3);

    });

    //Wait 1 seconds before checking state
    setTimeout(function(){
       that.refresh();
    }, this.updateInterval * 1000);
 }

}

 class makeChart{
    constructor(){
    //Chart Objects
        var ctx =  'testChart';
        //var ctx = document.getElementById('testChart');


    //Chart configurations
        var commonOptions = {
        scales: {
            xAxes: [{
                type: 'time',
                distribution: 'series',
                time:  {
                displayFormats:
                {
                second: 'h:mm:ss a'
                },
                unit:'second'
                }
            }],
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        },
        legend: {display: false},
        tooltips:{
            enabled: true
        }
    };

    //Chart instance
        this.testChart = new Chart (ctx,{
        type: 'line',
        data: {
        labels: [],                             //x axis
        datasets: [{
            label: "Particles Number10",          //change for each conc and part no
            data: [],                            //y axis
            fill: false,
            borderColor: '#343e9a',
            borderWidth: 1
        }]
     },
        options: Object.assign({}, commonOptions, {
        title:{
            display: true,
            text: "Particles Number10",          //change for each conc and part no
            fontSize: 18
            },
            maintainAspectRatio: false,
            responsive: false,
        })
     });
    console.log(this.testChart);

  };                                             //end of constructor


    addData (data) {

        if(data) {
    var today = new Date();
    var time =  today.getDate() +'/'+ (today.getMonth()+1)+ '/'+ today.getFullYear() +' '+ 
    today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();

    var chart_numberElements = 60;
    var chart_updateCount = 0;

    this.testChart.data.labels.push(time);
    this.testChart.data.datasets.push(data);

        if(chart_updateCount > chart_numberElements){
            this.testChart.data.labels.shift();
            this.testChart.data.datasets.shift();
        } else chart_updateCount++;

        //this.testChart.destroy();
        //this.testChart.update();

      }
    };
};

dashboard.html 调用画布的地方如下:

 <div class="modal-body">
   <canvas id="testChart" width="800" height="400"></canvas>
   </div>

我得到的不是图表,而是图片中显示的chart seen

【问题讨论】:

    标签: javascript chart.js


    【解决方案1】:

    Chart.js 在初始化时需要 &lt;canvas&gt; 元素。您似乎已经知道这一点,因为您拥有正确的代码,但它已被注释掉并替换为字符串:

    var ctx =  'testChart';
    //var ctx = document.getElementById('testChart');
    

    只需颠倒这些即可使其工作:

    //var ctx =  'testChart';
    var ctx = document.getElementById('testChart');
    

    当然,您需要确保 &lt;canvas&gt; 元素在运行时出现在 DOM 中。

    【讨论】:

    • 每当我按照你的建议反转它时,我都会得到 ctx = null。我以前试过,但它不起作用。
    • 在文档中他们提到初始化画布元素有不同的方式;
    • 如果是null,则该元素不存在于 DOM 中。确保在 DOM 准备好之后运行 javascript。
    • 在DOM中添加元素的唯一方法是文档中提到的四种方法之一吗?
    • 四种方式都没有添加元素——它们只能访问它。您需要自己添加元素,可以在 HTML 中静态添加,也可以通过 javascript 动态添加。但是dashboard.html 的代码 sn-p 显示了具有正确 id&lt;canvas&gt; 元素。所以问题可能是 when 您运行 javascript。如果它在 DOM 初始化之前运行,则该元素在运行时不存在。
    猜你喜欢
    • 2017-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-21
    • 2021-05-15
    • 2019-10-27
    • 2017-10-14
    相关资源
    最近更新 更多