如何从Highcharts重新绘制SVG渲染文本

时间:2019-05-13 07:46:29

标签: javascript svg highcharts

单击图例之一后,如何重绘SVG呈现的文本?我遇到的问题是SVG停留在该位置。
如果我点击其中一个传说,就会发生
enter image description here

我用来制作此图表的方法是:

  1. 创建一些空数组。
  2. 比较每个系列的值,以找出哪个系列的值最高
  3. 将最大值的xAxis推入数组。
  4. 在系列最高值旁边呈现SVG文本

这是我的代码示例:

       events: {
        render: function() {
          const chart = this,
            xAxis = chart.xAxis[0],
            yAxis = chart.yAxis[0],
            offsetX = 5;

          let customElems = chart.customElems || [],
            y,
            x,
            element;

          if (customElems.length) {
            customElems.forEach(elem => {
              elem.destroy();
            });

            customElems.length = 0;
          }

          var series_s_y = [];
          var series_d_y = [];
          var series_x   = [];
          var p          = [];
          chart.series[0].points.forEach((point, i) => {
            x = yAxis.toPixels(point.y) + 10;
            y = xAxis.toPixels(point.x);
            series_s_y.push(x);
            series_x.push(y);
          });

          chart.series[1].points.forEach((point, i) => {
            x = yAxis.toPixels(point.y) + 10;
            y = xAxis.toPixels(point.x);
            series_d_y.push(x);
          });
          for(i = 0;i < series_s_y.length; i++) {

            if(series_d_y[i] > series_s_y[i]) {
              p.push(series_d_y[i]);
            }
            else {
              p.push(series_s_y[i]);
            } 
            element = chart.renderer.text(`${PERSEN[i].toFixed(2)} %`, p[i], series_x[i]).attr({
              "fill": '#000',
              "font-weight": "bold",
              "class": "svg"
            }).add().toFront();

            customElems.push(element);
          }
          chart.customElems = customElems;
        }
      }

这是我的完整代码:
https://jsfiddle.net/d70ea4pq/
非常感谢您的任何帮助,非常感谢

1 个答案:

答案 0 :(得分:0)

重绘了文本元素,但还比较了隐藏系列的值。您可以在创建数组之前检查该系列是否可见:

for (i = 0; i < chart.series[0].points.length; i++) {

    if (series_d_y.length && series_s_y.length) {
        if (series_d_y[i] > series_s_y[i]) {
            p.push(series_d_y[i]);
        } else {
            p.push(series_s_y[i]);
        }
    } else if (series_d_y.length) {
        p.push(series_d_y[i]);
    } else if (series_s_y.length) {
        p.push(series_s_y[i]);
    }

    element = chart.renderer.text(
        `${PERSEN[i].toFixed(2)} %`,
        p[i],
        series_x[i]
    ).attr({
        "fill": '#000',
        "font-weight": "bold",
        "class": "svg"
    }).add().toFront();

    customElems.push(element);
}

实时演示: https://jsfiddle.net/BlackLabel/59gLzbpt/

API参考: https://api.highcharts.com/highcharts/chart.events.render