0

Need a javascript method to get color name.

Hoping javascript function should look like as follows

function (r,g,b)
{
  ....
  return <color name>; // like blue, cyan, magneta etc etc
}

4 Answers4

2

You can do that with color_classifier.js plug in. It works good and returns the name of nearest color that has name.

Just use like this

window.classifier = new ColorClassifier();
get_dataset('dataset.js', function (data){
    window.classifier.learn(data);
});
var result_name = window.classifier.classify("#aaf000");
PSR
  • 39,804
  • 41
  • 111
  • 151
1

If you know that the color values represent a combination that matches a color, you can use:

function getName(r, g, b) {
  switch ((r >> 5)*100+(g >> 5)*10+(b >> 5)) {
    case 400: return "maroon";
    case 700: return "red";
    case 750: return "orange";
    case 770: return "yellow";
    case 440: return "olive";
    case 404: return "purple";
    case 707: return "fuchsia";
    case 777: return "white";
    case 070: return "lime";
    case 040: return "green";
    case 004: return "navy";
    case 007: return "blue";
    case 077: return "aqua";
    case 044: return "teal";
    case 000: return "black";
    case 666: return "silver";
    case 444: return "gray";
  }
}

For color values that doesn't match a color, it may return a similar color (e.g. getName(230,240,250) returns "white"), or undefined.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

All standard known colors are listed here: http://www.w3.org/TR/CSS21/syndata.html#color-units

This is the smallest set of known colors, other platform may give more color keywords such as: http://www.w3schools.com/cssref/css_colornames.asp

Just choose your known color set, make them a (r, g, b) -> name map, this function is easy to implement

otakustay
  • 11,817
  • 4
  • 39
  • 43
0

//Function to convert hex format to a rgb color

function rgb2hex(rgb){
 rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
 return "#" +
  ("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
  ("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
  ("0" + parseInt(rgb[3],10).toString(16)).slice(-2);
}

Here is an example of how to use this code with jQuery:

document.write( rgb2hex($('#myElement').css('background-color')) );
// outputs: #222222

Now you can use this output and compare with any switch function to know about the name of this color

switch(color_code){
  case '#111111' : return ColorOne; break;
  case '#222222' : return ColorTwo; break;
  case '#333333' : return ColorThree; break;
}

//Function to convert hex format to a rgb color

function rgb2hex(rgb) {
var hexDigits = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];
rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
function hex(x) {
return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
}
return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

Refer this JSFiddle Link may this will help. --> ClickHere

Rubyist
  • 6,486
  • 10
  • 51
  • 86