Convert to hexadecimal colors

3

I want to put inside an array, the hexadecimal colors debts from a variable, so I have the all different colors inside the array.

I have the following example, but when using colors it does not work:

        var color=[];
        var n_elements =10 ;
        var inc=0;
        //65535 número maximo
        var step=parseInt(65535/n_elements);//#FFFFFF


        for(i=0;i<=65535;i+=step){
            var hexString = i.toString(16);
            color[inc]="#"+hexString;

            console.log(color[inc]);
            inc++;
        }
    
asked by anonymous 20.04.2015 / 23:58

1 answer

4

First, you should use 16777216 ( 256 * 256 * 256 - Red x Green x Blue) instead of 65535 ( 256 * 256 - missing one). Second, it is necessary to fill in the result with leading zeros, if the final result is less than 0x100000 :

        var data = [1,2,3,4,5]; // Exemplo


        var color=[];
        var n_elements = data.length ;
        var inc=0;
        var step=parseInt(16777216/n_elements);//#FFFFFF


        for(i=0;i<=16777216;i+=step){
            var hexString = i.toString(16);
          
            var pad = "000000";
            color[inc]="#"+(pad + hexString).slice(-6);

            document.body.innerHTML += (color[inc]) + "<br/>";
            inc++;
        }
    
21.04.2015 / 00:47