javascript - 在动态标记 Highcharts 上添加网格线

标签 javascript highcharts

我有这个动态图表,请问如何添加与标记一起移动的水平网格线?以及距当前标记大约 60 秒的垂直网格线?

    Highcharts.theme = {
     colors: ['#2b908f', '#90ee7e', '#f45b5b', '#7798BF', '#aaeeee', '#ff0066', '#eeaaee',
        '#55BF3B', '#DF5353', '#7798BF', '#aaeeee'],
     chart: {
       backgroundColor: 'transparent',
        style: {
           fontFamily: '\'Unica One\', sans-serif'
        },
        plotBorderColor: '#606063'
     },
     title: {
        style: {
           color: '#E0E0E3',
           textTransform: 'uppercase',
           fontSize: '20px'
        }
     },
     subtitle: {
        style: {
           color: '#E0E0E3',
           textTransform: 'uppercase'
        }
     },
     xAxis: {
        gridLineColor: '#707073',
        labels: {
           style: {
              color: '#E0E0E3'
           }
        },
        lineColor: '#707073',
        minorGridLineColor: '#505053',
        tickColor: '#707073',
        title: {
           style: {
              color: '#A0A0A3'

           }
        }
     },
     yAxis: {
        gridLineColor: '#707073',
        labels: {
           style: {
              color: '#E0E0E3'
           }
        },
        lineColor: '#707073',
        minorGridLineColor: '#505053',
        tickColor: '#707073',
        tickWidth: 1,
        title: {
           style: {
              color: '#A0A0A3'
           }
        }
     },
     tooltip: {
        backgroundColor: 'rgba(0, 0, 0, 0.85)',
        style: {
           color: '#F0F0F0'
        }
     },
     plotOptions: {
        series: {
           dataLabels: {
              color: '#B0B0B3'
           },
           marker: {
              lineColor: '#333'
           }
        },
        boxplot: {
           fillColor: '#505053'
        },
        candlestick: {
           lineColor: 'white'
        },
        errorbar: {
           color: 'white'
        }
     },
     legend: {
        itemStyle: {
           color: '#E0E0E3'
        },
        itemHoverStyle: {
           color: '#FFF'
        },
        itemHiddenStyle: {
           color: '#606063'
        }
     },
     credits: {
        style: {
           color: '#666'
        }
     },
     labels: {
        style: {
           color: '#707073'
        }
     },

     drilldown: {
        activeAxisLabelStyle: {
           color: '#F0F0F3'
        },
        activeDataLabelStyle: {
           color: '#F0F0F3'
        }
     },

     navigation: {
        buttonOptions: {
           symbolStroke: '#DDDDDD',
           theme: {
              fill: '#505053'
           }
        }
     },

     // scroll charts
     rangeSelector: {
        buttonTheme: {
           fill: '#505053',
           stroke: '#000000',
           style: {
              color: '#CCC'
           },
           states: {
              hover: {
                 fill: '#707073',
                 stroke: '#000000',
                 style: {
                    color: 'white'
                 }
              },
              select: {
                 fill: '#000003',
                 stroke: '#000000',
                 style: {
                    color: 'white'
                 }
              }
           }
        },
        inputBoxBorderColor: '#505053',
        inputStyle: {
           backgroundColor: '#333',
           color: 'silver'
        },
        labelStyle: {
           color: 'silver'
        }
     },

     navigator: {
        handles: {
           backgroundColor: '#666',
           borderColor: '#AAA'
        },
        outlineColor: '#CCC',
        maskFill: 'rgba(255,255,255,0.1)',
        series: {
           color: '#7798BF',
           lineColor: '#A6C7ED'
        },
        xAxis: {
           gridLineColor: '#505053'

        }
     },

     scrollbar: {
        barBackgroundColor: '#808083',
        barBorderColor: '#808083',
        buttonArrowColor: '#CCC',
        buttonBackgroundColor: '#606063',
        buttonBorderColor: '#606063',
        rifleColor: '#FFF',
        trackBackgroundColor: '#404043',
        trackBorderColor: '#404043'
     },

     // special colors for some of the
     legendBackgroundColor: 'rgba(0, 0, 0, 0.5)',
     background2: '#505053',
     dataLabelsColor: '#B0B0B3',
     textColor: '#C0C0C0',
     contrastTextColor: '#F0F0F3',
     maskColor: 'rgba(255,255,255,0.3)'
  };

  // Apply the theme
  Highcharts.setOptions(Highcharts.theme);


  jugalsLib = {
      defaults: {

          //interval: 24 * 60 * 60 * 1000,
          minValue: 0,
          maxValue: 10000,
          maxDeviationPercentOfRange: 5,
          numberOfSeries : 1
      },
      variables: {
          seriesCounter: 0
      },
      nextValue: function(currValue, options) {
          var settings = $.extend({}, jugalsLib.defaults, options || {}),
              nextValue,
              offset;

          currValue=currValue || (settings.maxValue + settings.minValue) / 2;      
          settings.maxDeviation =
                  settings.maxDeviation ||
                  (settings.maxValue - settings.minValue) * settings.maxDeviationPercentOfRange / 100;
          while (nextValue === undefined || nextValue < settings.minValue || nextValue > settings.maxValue) {
              offset = Math.random() * settings.maxDeviation * 2;
              nextValue = currValue - settings.maxDeviation + offset;
          }
          return nextValue;
      },
      createSeries: function(options) {
          var settings = $.extend({}, jugalsLib.defaults, options || {}),
              data = [],
              currValue,
              i, 
              time,
              valuePair;

          time = new Date().getTime();
          for (i = 0; i < settings.sampleCount; i++) {
              currValue = jugalsLib.nextValue(currValue, settings);
              valuePair = [];
              time += settings.interval;
              valuePair.push(time);
              valuePair.push(currValue);
              data.push(valuePair);
          }
          return {
              name: 'orvie test data',
              data: data
          };
      }    
  };

  jugalsLib.getBasicChartOptions = function(numberOfSeries,seriesOptions) {
      $("#container").mousemove(move);
      var options = {

          chart: {
              renderTo: 'container',

          },
          title: {
              text: 'test'
          },
          subtitle: {

              useHTML: true
          },

          xAxis: {
              type: 'datetime',
              tickPixelInterval: 150,
              gridLineWidth: 1,
              maxPadding: 0.5,
              navigator: true,

          },
          tooltip: {
              formatter: function () {
                  return '<b>' + this.series.name + '</b><br/>' +
                      Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
                      Highcharts.numberFormat(this.y, 2);
              }
          },
          plotOptions: {  



          line: {
            marker: {
                enabled: false,
                radius: 2,

            },
            states: {
                 hover: {
                     radiusPlus: 1,
                     lineWidthPlus: 0
                 },
             }

          },
          series: {
            lineWidth: 1.5,
            dataLabels: {
              align: 'center',
              enabled: false,



            },
             showInLegend: false, 
            hover: {
              lineWidthPlus: 0,
              animation: { "duration": 1 }

            },

             states: {
                  hover: {
                      halo: {
                          size: 1,
                          attributes: {
                              fill: Highcharts.getOptions().colors[2],
                              'stroke-width': 7,
                              stroke: Highcharts.getOptions().colors[4]
                          }
                      }

                  }
              },





          },


        }

      };
      numberOfSeries = numberOfSeries || jugalsLib.defaults.numberOfSeries;
      if(numberOfSeries>0){
          var i;
          options.series=[];        
          for(i=0;i<numberOfSeries;i++)
              options.series.push(jugalsLib.createSeries(seriesOptions));
      }
      return options;
  };


  var interval=1000;
  var a=0;
  var coor_x;
  var coor_y;

      Highcharts.setOptions({
          global: {
              useUTC: false
          }
      });

  var chartingOptions = {
      chart: {
          renderTo: 'container',
          events: {
              load: function() {
                  var series = this.series[0];
                  var series2 = this.series[1];
                  len = series.data.length;
                    this.addSeries({
                      id: 'end point',
                      type: 'scatter',
                      marker: {
                        enabled:true,
                        symbol:'circle',
                        radius:3,
                        fillColor:'white',
                        lineWidth:2,
                        states: { 
                            hover: { 
                                enabled: 'true',
                            },

                         },

                      },
                      data: [[
                        series.data[len - 1].x,
                        series.data[len - 1].y
                      ]]
                    }); 
                    var series3= this.get('end point');

                  setInterval(function() {
                      var l = chart.series[0].points.length;
                      var p = chart.series[0].points[l - 1];
                      var ix = p.x + interval;
                      var vv = jugalsLib.nextValue(p.y);

                      var w = ix + 30000,                
                              z = jugalsLib.nextValue(p.y);

                      var v;
                      a = 0;
                      if (a == 1) {
                          v = {
                              y: vv,
                              x: ix,                        
                            };               
                      }
                      else {
                          v = {
                              y: vv,
                              x: ix,
                          };

                      }

                      series.addPoint(v, true, true);
                      series3.data[0].setState('hover');
                      series3.data[0].update(v);
                      series3.data[0].setState();
                      series2.addPoint([w,z], true, true);

                      document.getElementById("coor_y").value = jugalsLib.nextValue(p.y).toFixed(4);
                  }, interval);


              },


          }
      },

    rangeSelector: {
              enabled: true,
              buttons: [{
                  count: 1,
                  type: 'minute',
                  text: '1M'
              }, {
                  count: 4,
                  type: 'minute',
                  text: '4M'
              }, {
                  type: 'all',
                  text: 'All'
              }],
              inputEnabled: false,
              selected: 0,

          },
      navigator:{
        enabled: true
          },


      exporting: {

              enabled: false
          },

          series: [{
            name: 'AAPZ',
            type: 'area',
            data: (function () {
                // generate an array of random data
                var data = [],
                    time = (new Date()).getTime(),
                    i;

                for (i = -300; i <= 0; i += 1) {
                    data.push([
                        time + i * 1000,
                        Math.random() * 10000
                    ]);
                }
                return data;
            }()),

            fillColor: {
                linearGradient: {
                    x1: 0,
                    y1: 0,
                    x2: 0,
                    y2: 1
                },
                stops: [
                    [0, Highcharts.getOptions().colors[0]],
                    [1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]
                ]
            },
                        marker: {
                enabled: false,
                radius: 2,

            },

        },{
            name: 'AAPL',
            type: 'area',
            enableMouseTracking: false,
            data: (function () {
                // generate an array of random data
                var data = [],
                    time = (new Date()).getTime()+30000,
                    i;

                for (i = -300; i <= 0; i += 1) {
                    data.push([
                        time + i * 1000,
                        Math.random() * 10000
                    ]);
                }
                return data;
            }()),
            gapSize: 5,
            color: 'transparent',


        }]



  };

  chartingOptions = $.extend({}, jugalsLib.getBasicChartOptions(1, {
      sampleCount: 300,
      interval: interval
  }), chartingOptions);
  var chart = new Highcharts.Chart(chartingOptions);

   var x=1;
   var count = 0;
   $("#btngreen").click(function() {
      var l = chart.series[0].points.length;
      var p = chart.series[0].points[l - 1];

     // document.getElementById("amount"+ id++ +"").value = jugalsLib.nextValue(p.y).toFixed(4);
      //document.getElementById("range").value = "up";
     var d = document.getElementById('order');
     var amount = document.getElementById("coor_y").value;
     var range = 'up';

     d.innerHTML += "Call&nbsp: <input type='text' maxlength='5' size='5' id='amount"+ x +"' value = "+amount+">&nbsp";
     d.innerHTML += "End: <input type='text' maxlength='5' size='5' id='end"+ x +"' value = '--rolling--'>&nbsp";
     d.innerHTML += "Range: <input type='text' id='range"+ x +"' value = "+range+" maxlength='4' size='4'><br>";

      p.update({
          marker: {
              symbol: 'Circle',
              fillColor: "#02CD0E",
              lineColor: "A0F0",
              radius: 2,
              enabled:true,
          },
           dataLabels: {
              align: 'right',
              enabled: true,
              shape: 'callout',
              padding: 1,
              overflow: "none",
              backgroundColor: '#02CD0E',
              style: {"color": "contrast", "fontSize": "10px" },
            formatter: function() {
                return document.getElementById("bet").value;
              }

          }

      });
      a = 1;

      if (x <= 1 ){
      countdown();
      }
      x++;
      count++;

      document.getElementById("count").value = count;

  });


    $("#btnred").click(function() {
      var l = chart.series[0].points.length;
      var p = chart.series[0].points[l - 1];

     var d = document.getElementById('order');
     var amount = document.getElementById("coor_y").value;
     var range = 'down';

     d.innerHTML += "Put&nbsp&nbsp: <input type='text' maxlength='5' size='5' id='amount"+ x +"' value = "+amount+">&nbsp";
     d.innerHTML += "End: <input type='text' maxlength='5' size='5' id='end"+ x +"' value = '--rolling--'>&nbsp";
     d.innerHTML += "Range: <input type='text' id='range"+ x +"' value = "+range+" maxlength='4' size='4'><br>";


      p.update({
          marker: {
              symbol: 'Circle',
              fillColor: "#FF0124",
              lineColor: "A0F0",
              radius: 2,
              enabled:true,
          },
          dataLabels: {
              align: 'right',
              enabled: true,
              shape: 'callout',
              padding: 1,
              overflow: "none",
              backgroundColor: '#FF0124',
              style: {"color": "contrast", "fontSize": "10px" },
            formatter: function() {
                return document.getElementById("bet").value;
              }

            }

      });
      a = 1;

      if (x <= 1 ){
      countdown();
      }
      x++;
      count++;

      document.getElementById("count").value = count;

  });


      function countdown() {

      var seconds = 60;

      function tick() {

      var counter = document.getElementById("counter");
          // alert(counter);
          seconds--;
          counter.innerHTML = "0:" + (seconds < 10 ? "0" : "") + String(seconds);
          if( seconds > 0 ) {
              setTimeout(tick, 1000);
              clearInterval(counter);

             if( seconds < 15 ){
             document.getElementById('btngreen').style.visibility = 'hidden';
             document.getElementById('btnred').style.visibility = 'hidden';
             }

          } 

          else {

            var count = document.getElementById("count").value

                var i;

                for(i = 1; i <= count; i++){

                 var amountid = "amount" + i; 
                 var rangeid = "range" + i;
                 var end = "end" + i;
                // console.log(amountid); 
                 var current = document.getElementById("coor_y").value;
                 var amount = document.getElementById(amountid).value;
                 var range =  document.getElementById(rangeid).value;

                 var endid = "end" + i;

                 document.getElementById(endid).value = document.getElementById("coor_y").value;
                  //console.log(amount);
                  //console.log(range) ;

                     if (current > amount && range == 'up'){
                           document.getElementById(amountid).style.color = "#66CD00"
                     }
                     else if (current > amount && range == 'down'){
                           document.getElementById(amountid).style.color = "#FF0000";
                     }
                     else if (current < amount && range == 'up'){
                           document.getElementById(amountid).style.color = "#FF0000";
                     }
                      else if (current < amount && range == 'down'){
                           document.getElementById(amountid).style.color = "#66CD00";
                     }


                }

          }
      }
      tick();

      }

      function move(event) {

        var x = event.pageX,
            y = event.pageY,
            labelPadding = [0, 0, 0, 0],
            path = ['M', chart.plotLeft, y,
                'L', chart.plotLeft + chart.plotWidth, y,
                'M', x, chart.plotTop,
                'L', x, chart.plotTop + chart.plotHeight];

        if (chart.crossLines) {
            // update lines
            if(chart.yAxis[0].toValue(y) > 0){
                chart.crossLines.attr({
                    d: path
                }).show();
            }
        } else {
            if(chart.yAxis[0].toValue(y) > 0){
                // draw lines
                chart.crossLines = chart.renderer.path(path).attr({
                    'stroke-width': 1,
                    stroke: 'white',
                    dashstyle: 'Dash',
                    zIndex: 10
                }).add();
            }
        }

        if (chart.crossLabel) {
            // update label
            chart.crossLabel.attr({
                y: y - 10,
                text: chart.yAxis[0].toValue(y).toFixed(2),
                zIndex: 9,
                right: 0
            }).show();
            console.log(chart.crossLabel);
        } else {
            // draw label
            chart.crossLabel = chart.renderer.text(chart.yAxis[0].toValue(y).toFixed(2), chart.plotBottom, chart.plotTop + chart.plotHeight + 12 + labelPadding[0]).css({
                color: 'white'
            }).add();
        }
    }

如果我的问题令人困惑,请参阅我附上的图片。 enter image description here

供您引用,这是我正在做的工作的副本 - https://jsfiddle.net/0hhfm32k/

最佳答案

Fiddle Demo用你的配置

输入 60000 时提前 6 秒而不是 60 秒,即 60 秒不显示

 setInterval(function() {

          var l = chart.series[0].points.length;
          var p = chart.series[0].points[l - 1];
          var ix = p.x + interval;
          var vv = jugalsLib.nextValue(p.y);

          var w = ix + 30000,
            z = jugalsLib.nextValue(p.y);

          var v;
          a = 0;
          if (a == 1) {
            v = {
              y: vv,
              x: ix,
            };
          } else {
            v = {
              y: vv,
              x: ix,
            };

          }

          series.addPoint(v, true, true);
          series3.data[0].setState('hover');
          series3.data[0].update(v);
          series3.data[0].setState();
          series2.addPoint([w, z], true, true);

          document.getElementById("coor_y").value = jugalsLib.nextValue(p.y).toFixed(4);

          yAxis.removePlotLine('avgLine');

          yAxis.addPlotLine({
            value: vv,
            /*label: {
              text: vv.toFixed(2),
              verticalAlign: 'middle',
              align: 'right',
              rotation: 0,
            },*/
            color: 'red',
            width: 4,
            dashStyle: 'Dash',
            id: 'avgLine'
          });
          xAxis.removePlotLine('ahLine');

          xAxis.addPlotLine({
            value: ix + 6000,
            /*label: {
              text: Highcharts.dateFormat('%I:%M:%S %p', ix+6000) ,
              verticalAlign: 'middle',
              align: 'right',
              rotation: 0,
            },*/
            color: 'red',
            width: 2,
            dashStyle: 'Dash',
            id: 'ahLine'
          });


        }, interval);

关于javascript - 在动态标记 Highcharts 上添加网格线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44583988/

相关文章:

javascript - Visual Studio.NET 2010 javascript 格式化

javascript - 重复凹凸贴图

highcharts - Highcharts条形图缩放不起作用

javascript - 将 String 值转换为 int 以在 highchart 中使用

javascript - WordPress 定制器预览脚本在初始页面加载时执行实时预览,而不是在我从预览窗口导航内页时执行实时预览

javascript - 在 AngularJS 中重置 textarea 后 Ng-model 不更新

javascript - useMemo 钩子(Hook)的流类型

javascript - 自定义 HighCharts 中各个系列的颜色

javascript - Highcharts - 在 x 轴和 y 轴上隐藏系列 "points"(标签)

javascript - 如何在x轴上添加多个文本