2016-07-25 94 views
1
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script> 
    <body> 
    <div id="myDiv2" style="width: 600px; height: 650px;"><!-- Plotly chart will be drawn inside this DIV --></div> 
    </body> 
    <script> 
    var socket = io(); 
    socket.on('temp', function(temp){ 
     $('#messages').html(temp); 
     var layout = { 
    title: "Live Data Streaming", 
    xaxis: { 
     title: "X Axis", 
     titlefont: { 
     family: "Verdana, Sans-serif", 
     size: 18, 
     color: "#7f7f7f" 
     } 
    }, 
    yaxis: { 
     title: "Live Data", 
     titlefont: { 
     family: "Verdana, Sans-serif", 
     size: 18, 
     color: "#7f7f7f" 
     } 
    } 
    }; 
    var i=0; 
    var loop = setInterval(function() { 
    var trace1 = { 
    x: [i], 
     y: [temp], 
     type: 'line' 
     }; 
     i++; 
    }, 5000); 

     var data = [trace1]; 
     Plotly.newPlot('myDiv2', data, layout); 
    }); 
      </script> 

套接字正在偵聽變量temp。我希望每五秒鐘將這個臨時變量生成一個圖表。現在,我正在積極使用並每五秒設置一次間隔,但圖形不會顯示在我的html中。如果我刪除setInterval,圖表顯示正常,但舊的臨時替換爲新的臨時而不是繼續圖形。任何想法如何在Java腳本中直播這些數據。在javascript中實時流式傳輸

回答

1
var plotDiv = document.getElementById('myDiv2'); 
layout = { 
    hovermode:'closest', 
    title: "Live Data Streaming", 
    xaxis: { 
    title: "X Axis", 
    autorange:true, 
    titlefont: { 
     family: "Verdana, Sans-serif", 
     size: 18, 
     color: "#7f7f7f" 
    } 
    }, 
    yaxis: { 
    title: "Live Data", 
    autorange:true, 
    titlefont: { 
     family: "Verdana, Sans-serif", 
     size: 18, 
     color: "#7f7f7f" 
    } 
    } 
}; 
var data = [{ 
    x: [0], 
    y: [0] 
}]; 

Plotly.plot(plotDiv, data, layout); 

var i = 1; 
setInterval(function(){ 
    socket.once('temp', function(temp){ 
    var update = {x: [[i]],y: [[temp]]}; 
    i++; 
    Plotly.extendTraces(plotDiv, update, [0], 100); 
    }); 

    $('#stop').click(function() { 
    clearInterval(loop); 
    }); 
    }, 5000); 

    plotDiv.on('plotly_click', function(data){ 
    var pts = ''; 
    for(var i=0; i < data.points.length; i++){ 
     pts = 'x = '+data.points[i].x +'\ny = '+ 
     data.points[i].y.toPrecision(4) + '\n\n'; 
    } 
    alert('Data point clicked is located at:\n\n'+pts); 
    }); 

這應該會直播流數據完美地使用JavaScript。