我正在尝试使用人力车来创建一个不错的占位图,该图显示实时更新随机数据,如下所示:

var series = [[], []];
var random = new Rickshaw.Fixtures.RandomData(150);

for(var i = 0; i < 80; i++) {
    random.addData(series);
}

var throughput = new Rickshaw.Graph( {
    element: document.querySelector("#throughput_chart"),
    width: "300",
    height: "200",
    renderer: "line",
    series: [{
        color: "gold",
        data: series[0]
    }]
});

var alerts = new Rickshaw.Graph( {
    element: document.querySelector("#alerts_chart"),
    width: "300",
    height: "200",
    renderer: "line",
    series: [{
        color: "red",
        data: series[1]
    }]
});

throughput.render();
alerts.render();

setInterval(function() {
    random.addData(series);
    throughput.update();
    alerts.update();
    /* XXX: This causes the data to stop drawing properly
    series.forEach(function(s) {
        s.shift();
    });
    */
}, 1000);

除已注释掉的部分外,此方法有效。实际上,它一直在添加数据,这意味着图形变得越来越拥挤。我希望每次添加新项到末尾时都可以删除第一项,以使图形具有相同数量的数据点,但是当我将该代码放入其中时,会导致图形无法显示即使console.log显示数组仍然充满数据,也可以显示任何数据。

如何进行这项工作,以便一次只能显示固定数量的数据点?

最佳答案

在Rickshaw(http://code.shutterstock.com/rickshaw/examples/fixed.html)文档的示例示例之后,我整理了一些与您需要的东西类似的东西:

JS FIDDLE

var tv = 50;

var throughput = new Rickshaw.Graph({
    element: document.querySelector("#throughput_chart"),
    width: "300",
    height: "200",
    renderer: "line",
    series: new Rickshaw.Series.FixedDuration([{
        name: 'one', color: 'gold'
    }], undefined, {
        timeInterval: tv,
        maxDataPoints: 100,
        timeBase: new Date().getTime() / 1000
    })
});

var alerts = new Rickshaw.Graph({
    element: document.querySelector("#alerts_chart"),
    width: "300",
    height: "200",
    renderer: "line",
    series: new Rickshaw.Series.FixedDuration([{
        name: 'one', color: 'red'
    }], undefined, {
        timeInterval: tv,
        maxDataPoints: 100,
        timeBase: new Date().getTime() / 1000
    })
});

for(var i = 0; i < 100; i++){
    addRandomData(throughput);
    addRandomData(alerts);
}

throughput.render();
alerts.render();

setInterval(function () {

    addRandomData(throughput);
    addRandomData(alerts);
    throughput.render();
    alerts.render();

}, tv);

function addRandomData(chart) {
    var data = {
        one: Math.floor(Math.random() * 40) + 120
    };
    chart.series.addData(data);
}

关于javascript - 实时更新人力车图,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16944128/

10-11 16:54