Convert to hexadecimal colors

Asked

Viewed 308 times

3

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

I have the following example, but using colors 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++;
        }

1 answer

4


First of all, you should wear 16777216 (256 * 256 * 256 - Red x Green x Blue) instead of 65535 (256 * 256 - missing one). Second, it is necessary to fill the result with zeros on the left, 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++;
        }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.