mardi 2 février 2016

method to create random colors according to some sets

In my javascript file, i have a set of couples eache constituted by a letter and a number, for exemple : {(A,5), (B,7), ..., (Z,3)}.

For every couple (A,x) I have x divs in my html with a style = "background-color: {{object.color}}".

I'd like to write a method that randomly computes x colors for each couple (A,x) such that :

  • each color is enough different from the others to distinguish all of them.
  • every colors of a same couple are enough close to identify this couple.

For exemple : I have this couples : {(A,5), (B,4), (C,10)} so I have 19 divs in my html. For all 5 divs of set A I compute a color of blue tint, for all 4 divs of set B I compute a color of green tint, and for all 10 divs of set C I compute a color of red tint.

Of course you don't know the couples by advance :)

Is there a way to do that maybe using the RGB value of each color on css or something like this ?

for the moment I have only made a method where I pick each color completly randomly only avoiding colors that are too much dark or too much white and with a loop to garantee a color already taken can't be taken twice :

   function(){
        var cb=0;
        var cr=0;
        var cg=0;
        var minEcart=40;
        var testB=true;
        var cptI=0;
        while(testB){
            testB=false;
            cr=Math.round(Math.random()*170) + 85;
            cb=Math.round(Math.random()*170) + 85;
            cg=Math.round(Math.random()*170) + 85;
            for(var j=0; j<$scope.colorAlreadyGiven.length;j++){
                if(($scope.colorAlreadyGiven[j][0]-cb>=-minEcart)&&
                    ($scope.colorAlreadyGiven[j][0]-cb<=minEcart)&&
                    ($scope.colorAlreadyGiven[j][1]-cg>=-minEcart)&&
                    ($scope.colorAlreadyGiven[j][1]-cg<=minEcart)&&
                    ($scope.colorAlreadyGiven[j][2]-cr>=-minEcart)&&
                    ($scope.colorAlreadyGiven[j][2]-cr<=minEcart)){
                        testB=true;
                        cptI++;
                        if(cptI>=50){
                            testB=false;
                        }
                }
            }
        }
        $scope.colorAlreadyGiven.push([cb,cg,cr]);
        return "#"+(cb+cg*256+cr*65536).toString(16);
  }

Thanks for your attention.




Aucun commentaire:

Enregistrer un commentaire