| 注册
请输入搜索内容

热门搜索

Java Linux MySQL PHP JavaScript Hibernate jQuery Nginx
jopen
11年前发布

Highcharts Stock 实时图表监控JS

higcharts 是一个图表展示框架,支持基本图形,支持静态、动态等数据,文档很详细,实例代码很多,容易上手,这个JS是我的一个获取实时动态数据的JS脚本,依赖JQUERY.

第一次加载时从数据库中抽取监控数据,JS生成昨天及上周同天的对比数据。 每分钟动态更新图表。

Highcharts Stock 实时图表监控JS

var bistock = bistock || {};  $(function () {          var seriesOptions = [],     // 历史对比曲线 0当前,1昨天,7上周          periods = [0, 1, 7],           impl,        config,    seriesCount = 0,     charts = [],    get_data_url = false,    update_url = false;      impl = {      config_chart: function() {      Highcharts.setOptions({       colors: ['#DDDF00', '#058DC7', '#50B432', '#ED561B', '#24CBE5', '#64E572', '#FF9655', '#FFF263', '#6AF9C4'],      global: { useUTC: false  }      });      },     debug: function(msg, vars) {     console.log(msg);     if(vars) {      $.each(vars, function(i, v) {       console.log(i+':'+v);      });     }    },    /**     * 生成监控图表     * @id 图表id     * @div 图表渲染的div     */    generate_chart: function(id, div) {        var tmp_count = 0;     $.ajax({       type: "get",       async: false,       data: {menuid: id},       url: get_data_url,       dataType: "json",       success: function (response) {       $.each(response.rs, function (series_name, item) {              // 添加历史对比数据              $.each(periods, function (j, period) {                seriesOptions[seriesCount] = {          name: impl.get_series_name(period) + series_name,          data: (period === 0) ? item.data : impl.get_series_data(item.data, period),          type: 'spline',          lineWidth: (seriesCount == 0 || seriesCount == 3) ? 4 : 2         };         impl.debug("Series info: ", {'name':seriesOptions[seriesCount]['name'], 'number': seriesCount});         seriesCount++;        });         });       impl.createChart(seriesOptions, div, id);             seriesOptions = [];       seriesCount = 0;       },       error: function(){        alert('Fail to render to chart '+id);       }      });    },    /**     * 获取图表曲线的名称     * @period 图表曲线周期0,1,7     */          get_series_name: function (period) {                return (period == 0) ? '当天' : ((period == 1) ? '昨天' : '上周同天');          },    /**     * 获取图表的数据     * @data 原始数据     * @period 图表曲线周期0,1,7     */          get_series_data: function (data, period) {                            var new_series_data = [],                  time_offset = period * 86400 * 1000,                  now = (new Date()).getTime();                                $.each(data, function (i, item) {                  // 删除某段时间的数据,然后整体偏移.                  var point_data;                  if (item[0]+time_offset < now+8*3600*1000-600*1000) {       new_series_data[i] = [item[0] + time_offset, item[1]];                  }                              });                 return new_series_data;          },    /**     * 动态更新图表     */    updateChart: function(menuid) {     setInterval(function() {                 $.ajax({           url: update_url,           type: 'GET',        data: {menuid: menuid},           async: false,                 contentType: "application/json; charset=utf-8",           dataType: 'JSON',           success: function(response) {                      if (!response.rs) {          impl.debug('No Data');                 impl.debug("Chart Info: ",{'menuid': menuid, 'time': response.happen_time});          return;         }                  impl.debug("Chart Info: ",{'menuid': menuid, 'time': response.happen_time});               var updateCount = 0;                   $.each(response.data, function(i, items){          $.each(items, function(j, item) {                     impl.debug("Series info: ", {'data': item, 'number': updateCount});           charts[menuid].series[updateCount].addPoint(item, true, true);                    updateCount++;                   });         });         updateCount = 0;           },           cache: false         });         }, 60000);     },    /**     * 从缓存中读取历史数据     * @id menuid     * @period 1,7     * @num 数据序列 0,1,2...     * @size 曲线的大小     * @time 当期时间     * @return 返回一个点的数据     */    get_history_point: function(id, period, num, size, time) {           var idx = (size == 1) ? 0 : num;     var tmp_size = cacheData[id][idx].length;     // fix the time     var tmp_point_data = cacheData[id][idx][tmp_size-period*144+1][1];       return [time, tmp_point_data];    },    rand_point: function(max) {     var x = (new Date()).getTime(), // current time      y = Math.round(Math.random() * max);     return [x,y];    },    /**     * 创建图表     * @seriesData 图表数据     * @div 渲染到div     * @id 图表的唯一id        */          createChart: function (seriesData,div,id) {     charts[id] = new Highcharts.StockChart({      chart: {                        animation: Highcharts.svg,                    marginRight: 10,                   renderTo: div,                   events: {                       load: impl.updateChart(id)                   }               },          colors: (config['colors']) ? config['colors'] : ['#AA4643','#4572A7','#89A54E','#80699B','#3D96AE','#DB843D','#92A8CD','#A47D7C','#B5CA92'],                  rangeSelector: {                      buttons: [{        count: 1,        type: 'hour',        text: '1h'       },{        count: 8,        type: 'hour',        text: '8h'       }, {        count: 1,        type: 'day',        text: '1d'       }, {        count: 1,        type: 'week',        text: '1w'       },{        count: 1,        type: 'month',        text: '1m'       },{        count: 3,        type: 'month',        text: '3m'       },{        type: 'all',        text: 'All'       }],       inputEnabled: false,       selected: 1                  },      legend: {       borderWidth: 0,       enabled: true      },                  yAxis: {                          min: 0,                      plotLines: [{                          value: 0,                          width: 2,                          color: 'silver'                      }],       labels: {        enabled: config['isEnabled']         }                  },                    plotOptions: {                      series: {                          //compare: 'percent'                      }                  },                    tooltip: {       pointFormat: config['isEnabled']            ? '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b><br />'            : '<span style="color:{series.color}">{series.name}</span><br />',                      valueDecimals: 2                  },                    series: seriesData              });          },    run: function() {       impl.config_chart();     $.each(config['names'], function(i, name){      impl.generate_chart(name, 'container_'+i);     });    }      };   bistock = {    init: function(vars) {     config = vars;     impl.run();    }   };  });

来自:http://my.oschina.net/ym80/blog/201324

 本文由用户 jopen 自行上传分享,仅供网友学习交流。所有权归原作者,若您的权利被侵害,请联系管理员。
 转载本站原创文章,请注明出处,并保留原始链接、图片水印。
 本站是一个以用户分享为主的开源技术平台,欢迎各类分享!
 本文地址:https://www.open-open.com/lib/view/open1392882562148.html
图表/报表制作 Highcharts