LCaraway - 9 months ago 46

Javascript Question

I would like to be able to call a function that takes a base color and returns an array of values that correspond to different shades of the same color. The array can contain either hex values or rgba() values. I would like to be able to input the amount of desired shades as well. The amount of shades would then also be able to be used as a metric to increment the shade. For example if I wanted the output have 3 different shades, the 1st shade would be 1/3 of the base.. however that math would work... Additionally, In some situations the 1st shade may need to be 100% transparent so I would like to accept an argument for the initial alpha. I've organized what I think would be the basic logic of the function but the math is unclear to me.

`var buildColorStops = function (baseColor,numberOfValues,initialAlpha) {`

var b = baseColor;

var n = numberOfValues //expected number of colors in the output. If n was 3 results would be [light blue, blue(base), dark blue] (# or rgba will work)

var d = 1 / n; // if number of values was 5 d would represent 1/5 of the base.

var ia = initialAlpha; // some situations may require the first color to be 100% transparent

var outputArray = [];

var i = 0;

while (i < n) {

if (i == 0) {

//...math on base color & incorporate initial alpha

outputArray.push("result of math on base")

}

else {

//...math on base color by incrementing d or 1/n

outputArray.push("result of math on base")

}

}

return outputArray;

}// end of buildColorStops

Answer Source

Shades can be generated by maintaining the ratio of the colors same. Suppose that your base color has `(r,g,b)`

red, green, blue values.

So the the ratio between the components is `r:g:b`

. If you want to generate 10 shades then your shades would be.

```
(r/10, g/10, b/10)
(2*r/10, 2*g/10, 2*b/10)
(3*r/10, 3*g/10, 3*b/10)
(4*r/10, 4*g/10, 4*b/10) and so on
```

That's for the darker shades.

for lighter shades

```
(11*r/10, 11*g/10, 11*b/10)
(12*r/10, 12*g/10, 13*b/10)
(13*r/10, 13*g/10, 13*b/10) and so on
```

Check resulting values of r,g, b to not be more than 255 as lightening them increases their values.

In fact to avoid going over 255, you can check whichever of r,g,b is maximum and use that value to generate shades.

```
var max = Math.max(r,Math.max(g,b));
var step = (255 - max) / 10
(r * step, g * step, b * step)
(r * step * 2, g * step * 2, b * step * 2)
(r * step * 3, g * step * 3, b * step * 3)
```