Real-time data with D3

前端 未结 1 2078
悲哀的现实
悲哀的现实 2021-02-10 01:22

I was wondering if I could use the D3 library with real-time data my server would be sending via websockets. I can\'t see any documentation or examples that demonstrate this. My

相关标签:
1条回答
  • 2021-02-10 01:37

    I haven't used websockets with D3 (yet) but it looks like you're expecting d3.json to be a JSON parser. It's not - it's an AJAX loader that delegates to JSON.parse for parsing. So you probably want something like:

    var ws = new WebSocket("ws://localhost:8888/ma");
    
    var data = [];
    
    ws.onmessage = function(evt) {
        // append new data from the socket
        data.push(JSON.parse(evt.data));
        update();
    };
    
    // now use the standard join pattern to deal with updates
    function update() {
        var chunk = d3.selectAll('p')
            .data(data);
    
        // entry might be all you need, if you're always appending
        chunk.enter().append('p')
            .text(function(d) { return d; });
    
    }
    
    0 讨论(0)
提交回复
热议问题