项目需求
Echarts图表自动获取服务器端推送的数据,实现图表的自动渲染更新;
前端代码
引入JS包
<script src="js/jquery-3.3.1.min.js"></script> <script src="js/echarts.min.js"></script>
HTML代码
<div id="main" style="width: 1000px;height: 600px;"></div>
JS代码
webSocket连接函数封装;
//webSocket连接; function WebSocketServer() { var wsClient = null; //WS客户端对象 //判断是否支持WebSocket if (!window.WebSocket) { window.WebSocket = window.MozWebSocket; } if (window.WebSocket) { wsClient = new WebSocket('ws://127.0.0.1:9090'); wsClient.onmessage = function (e) { //console.log(e.data); //图表渲染数据格式处理; var newData = JSON.parse(e.data); var dataName = [], dataList = []; for (var i = 0; i < newData.length; i++) { dataName.push(newData[i].vname); dataList.push(newData[i].vdata); } //console.log(newData[0].vdata); //渲染图表; getLine(dataName, dataList); }; //连接服务器; wsClient.onopen = function () { console.log('WS客户端已经成功连接到服务器上'); wsClient.send('getPeerInfo'); //向WS服务器发送一个消息 }; //断开服务器; wsClient.onclose = function (e) { console.info("WS客户端到服务器的连接已经断开" + JSON.stringify(e)); }; } else { alert("你的浏览器不支持 WebSocket!"); } }
Echarts图表函数封装
/*Echarts*/ function getLine(dataName, dataList) { var myChart = echarts.init(document.getElementById('main')); var option = { tooltip: { trigger: 'axis', axisPointer: { type: 'cross', label: { backgroundColor: '#6a7985' } } }, xAxis: { type: 'category', boundaryGap: false, data: dataName }, yAxis: { type: 'value' }, series: [{ data: dataList, type: 'line' }] }; myChart.setOption(option); window.addEventListener("resize", function () { myChart.resize(); }); }
Done!