Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choosing the most colorful color in javascript

I have a group of colors and I want to find their relative colorfulness. Could anyone show me an example in javascript? Many thanks!

like image 249
MachineElf Avatar asked Jan 11 '11 14:01

MachineElf


2 Answers

// You can compare colors by their saturation and brightness-

function rgbtoHsv(rgb){
    var c= rgb.match(/\d+/g),
    r= c[0]/255, g= c[1]/255, b= c[2]/255,
    max= Math.max(r, g, b), min= Math.min(r, g, b),
    h= 0, s= 0, v= max;
    if(max!= min){
        var d= max-min;
        s= d/max;
        switch(max){
            case r: h= (g-b)/d +(g< b? 6: 0);
            break;
            case g: h= (b-r)/d + 2;
            break;
            case b: h= (r-g)/d + 4;
            break;
        }
    }
    return [Math.round(h*60), Math.round(s*100), Math.round(v*100)];
}
function sortColors(a, b){
    var a1= rgbtoHsv(a), b1= rgbtoHsv(b);
    return  (b1[1]+b1[2])-  (a1[1]+a1[2]);
}

var colors=['rgb(255,0,0)','rgb(150,150,150)','rgb(0,200,100)','rgb(0,255,255)']; // colors.sort(sortColors).join('\n')

/*  returned value: (most to least 'colorful')
rgb(255,0,0)
rgb(0,255,255)
rgb(0,200,100)
rgb(150,150,150)
*/
like image 132
kennebec Avatar answered Nov 19 '22 17:11

kennebec


This function returns the saturation (from 0.0 to 1.0) given the RGB values:

 function saturation(r,g,b) {
     var minVal = Math.min(r, g, b);
     var maxVal = Math.max(r, g, b);
     var delta = maxVal - minVal;
     if (maxVal === 0 ) {
          return 0;
     } else {
          return (delta / maxVal);
     }
 }

I know you asked for colorfulness, but this could be a good stating point. (I actually didn't knew the difference, thanks for pointing out that wikipedia page)

like image 30
Omiod Avatar answered Nov 19 '22 17:11

Omiod