Home > Mobile >  How to dynamically calculate gradient percentage
How to dynamically calculate gradient percentage

Time:12-17

I have an array which has dynamic values from server

let arr = ['#eee','#fff','#aaa']
or sometimes,
let arr = ['#eee','#fff','#aaa','#eee','#fff','#aaa']

Now, I need to calculate the gradient values for equal distribution of colors. I did something like below which is giving some wrong value.

let arr = ['#eee','#fff','#aaa','#eee','#fff','#aaa']

let gper = parseFloat(100/arr.length)

let c_arr = arr.map((k, i) => {  return `${k} ${parseFloat(gper * i--)}% ${parseFloat(gper * i)}%`})
               .toString()
               
console.log(`linear-gradient(to left, ${c_arr})`)

Is there a best way to fix this

CodePudding user response:

If you want even distribution of colors in your gradient, it is not necessary to specify percentage at all. The browser does this by default.

You can simply do something like this:

`linear-gradient(to left, ${arr.join()})`

CodePudding user response:

There is just a slight alteration needed to the calculation - in the question the first value went negative.

This snippet spells it out in a loop just to make it a bit clearer - the values need to start at 0 not -gper.

let arr = ['#eee', '#fff', '#aaa', '#eee', '#fff', '#aaa']

let gper = parseFloat(100 / arr.length)

let c_arr = '';
for (let i = 0; i < arr.length; i  ) {
  c_arr  = ((i == 0) ? '' : ', ')   arr[i]   ' '   i * gper   '%'   ' '   (i   1) * gper   '%';
}
console.log(`linear-gradient(to left, ${c_arr})`);

The result is:

linear-gradient(to left, #eee 0% 16.666666666666668%, #fff 16.666666666666668% 33.333333333333336%, #aaa 33.333333333333336% 50%, #eee 50% 66.66666666666667%, #fff 66.66666666666667% 83.33333333333334%, #aaa 83.33333333333334% 100%)
  • Related