1

I need to recover all the values bewteen a given color and white. For example, from this blue (#4A90E2) until plain white (#ffffff), and get values dependeing on a certain number of elements.

If I have 6 elements, I would need 6 colors being those a percentage representing the 6 elements I have, every single one a bit lighter than the previous one as if you divide the spectrum between the two first colors in six equal parts.

Any ideas?

Thank you in advanced!

  • Check if this helps https://stackoverflow.com/a/17527156/2968762 – Abhi Sep 29 '17 at 14:06
  • 2
    Colors are only hexa numbers, so you can convert them to dec number, calculate the difference between the 2 numbers, divide by X (you will get the gap you need to add to get the next color). Then you convert back to hexa to get your color – soywod Sep 29 '17 at 14:09

2 Answers2

0

RGB to hex and hex to RGB

In this post, the answer shows functions to transform RGB to hex and back. Using these functions, one can get the difference.

Let's assume we have #007FFF, if we want to divide this into 2 steps, first we get the numerical values: R: 0, G: 127, Blue: 255 now we get the difference from white( 255): 255-0 = 0, 255- 127=128, 255-255=0

These numbers can now be divided by however many steps you want. Using 2 steps this would be: 127.5, 64, 0

Now one can iterate over the base numbers we transformed to RGB, and add the step value every iteration for a smooth step.

function getColorSteps(color,steps) {
   var rgb=hexToRgb(color);
   var deltaRgb = { r: 255-(rgb.r/steps), g: 255-(rgb.g/steps), b:255-(rgb.b/steps) };
   colors = [];
   for (var i = 1; i <= steps; i++) {       
       colors.push({r:rgb.r+deltaRgb.r*i,g:rgb.g+deltaRgb.g*i,b:rgb.b+deltaRgb.b*i});
   }
   return colors;
}
0

This function works out for you:

function getColors(color, n) {
    // i'm supposing your color is a string in format '#XXXXXX'
    const white = 0xFF;
    const redComponent = parseInt("0x" + color[1] + color[2]);
    const greenComponent = parseInt("0x" + color[3] + color[4]);
    const blueComponent = parseInt("0x" + color[5] + color[6]);

    var colors = [];
    for(var i=1; i<=n; i++) {
        var red = white - (i*(white-redComponent))/(n+1) + 0xf00;
        var green = white - (i*(white-greenComponent))/(n+1) + 0xf00;
        var blue = white - (i*(white-blueComponent))/(n+1) + 0xf00;

        colors.push("#" + red.toString(16).substr(1,2) + green.toString(16).substr(1,2) + blue.toString(16).substr(1,2));
    }
    return colors;            
}
Canta
  • 1,480
  • 1
  • 13
  • 26