Highcharts linearGradient fill with fixed upper bo

2019-09-07 02:27发布

I'm looking to achieve an effect similar to that in this example.

However, the above example uses a gradient that is relative to the visible plot. So the 0 stop color is used at the peak of the visible plot (whatever the actual value of the peak), and the 1 stop color is used at the base.

Say I have data that can range from 0 to 100 (e.g. a percentage). I want to be able to specify that "dark" is always used for a value of 100, while "light" is always used for a value of 0.

So, if my visible data only ranges from 0 to 20, then this is all filled with a light-ish gradient colour (at the lower end of the gradient spectrum)... I don't want it to be filled from light to fully dark.

Any way to achieve this?

1条回答
小情绪 Triste *
2楼-- · 2019-09-07 03:08

To achieve such gradient, you need to do a few things.

  1. Gradient units should be switched to userSpaceOnUse.
  2. x1, y1, x2, y2 should point to the points where the plot area starts and ends.

You do not know what would be the plot area, so you have to set the gradient on load event.

function() {
  this.series[0].update({
    fillColor: {
      linearGradient: [0, 0, 0, this.plotHeight]
    }
  });
}

example: http://jsfiddle.net/qhuee8uf/1/

Now, the gradient has fixed x/y attributes, what means that the gradient will not be responsive. To have a gradient which will work with a resizing chart, you should recalculate gradient on redraw event.

Also, I have found that updating gradient in the series does not update the gradient but creates a new one - which might be not be the best behaviour to have.

Instead, you can modify the gradient attributes directly

function adjustGradient() {
  document.getElementsByTagName('linearGradient')[0].setAttributeNS(null, 'y2', this.plotHeight);
}

chart: {
  events: {
    load: adjustGradient,
    redraw: adjustGradient
  }
},

example: http://jsfiddle.net/qhuee8uf/

查看更多
登录 后发表回答