`

javascript - tricks to deal with colors

阅读更多

There are a couple of ways to represent a color information. and it always cause confusion across different browsers.

 

 

• rgb(R,G,B) - Where R, G, B are numbers from 0 to 255.

• rgb(R%,G%,B%) - Where R, G, B are numbers from 0% to 100%.

• #RRGGBB - Where RR, GG, BB are hexadecimal representations of the numbers 0 through 255.

• #RGB - Where R, G, B are hexadecimal representations similar to the previous one, but in shorthand

(e.g. #F54 is equal to #FF5544).

• red, blue, etc. - The name representing a set of RGB values.

 

the following code is from the jQuery and is written by jQuery's color plugin's author, I am showing it here to manifest just a reminder of the different of different colors. 

 

/**************************************
*@Name: expandoattr.js
*@Summary
*  this function shows hwo you can parse colors in different format to a single format.
*
*
***************************************/
var num = /rgb\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*\)/,
    pc = /rgb\(\s*([0-9.]+)%\s*,\s*([0-9.]+)%\s*,\s*([0-9.]+)%\s*\)/,
    hex = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/,
    hex2 = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/;
// Parse strings looking for color tuples [255,255,255]
function getRGB(color) {
  var result;
  // Look for rgb(num,num,num)
  if (result = num.exec(color))
    return [parseInt(result[1]), parseInt(result[2]),
parseInt(result[3])];

  // Look for rgb(num%,num%,num%)
  if (result = pc.exec(color))
    return [parseFloat(result[1]) * 2.55, parseFloat(result[2]) * 2.55,
parseFloat(result[3]) * 2.55];
  // Look for #a0b1c2
  if (result = hex.exec(color))
    return [parseInt(result[1], 16), parseInt(result[2], 16),
parseInt(result[3], 16)];
  // Look for #fff
  if (result = hex2.exec(color))
    return [parseInt(result[1] + result[1], 16),
parseInt(result[2] + result[2], 16),
parseInt(result[3] + result[3], 16)];
  // Otherwise, we're most likely dealing with a named color
  return colors[color.replace(/\s+/g, "").toLowerCase()];
}
// Map color names to RGB values
var colors = {
  aqua: [0, 255, 255],
  azure: [240, 255, 255],
  beige: [245, 245, 220],
  black: [0, 0, 0],
  blue: [0, 0, 255],
  // ... snip ...
  silver: [192, 192, 192],
  white: [255, 255, 255],
  yellow: [255, 255, 0]
};
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics