Color Conversion in JavaScript

Color Conversion Algorithms in JavaScript

RGB to Hexadecimal

RGB Color Values

RGB uses color values of base 10 numbers. It is generally easier for humans to understand base 10. In base 10, the number 15 is written 15, in hex, 15 is written F or 0F.

RGB also uses color values as percentages. rgb(100%, 100%, 0%) is equivalent to rgb(255, 255, 0), which is equivalent to #FFFF00 in hexadecimal notation.

In RGB, the numbers 0-15 are 0-15 (base 10).

Hexadecimal Color Values

Hexadecimal color values have as many possible values as rgb colors. The way they are written is #ffffff. Hexadecimal color values may optionally be written with only three digits, as in #fff. When only three digits are used, each digit is doubled, so for example, #356 would really be #335566.

In hex, the numbers 0-15 are written 0-F.

Comparing Hexadecimal(Base 16) to Base 10
rgb 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
hex 0 1 2 3 4 5 6 7 8 9 A B C D E F

Look at the comparison table above for a comparison of hexadecimal to base 10. Hexadecimal numbers are the same as base 10 numbers until 10. In hexadecimal, 10 is A, 11 is B, 12 is C, 13 is D, 14 is E, and 15 is F.

Uses of RGB Color Values

Base 10 numbers are easy to work with. Using rgb (base 10) facilitates all sorts of neat things like looping through colors.

Uses of Hexadecimal Color Values

Almost all web designers (including myself) use hexadecimal color. I honestly don't know why.

One obvious reason to use JavaScript for converting rgb colors to hex is compatibility. Moz & Netscape (as of v0.9.5 and v6.2) internally convert all hex colors to rgb. Converting the rgb value back to hex allows you to compare style values in hex.

Colors sometimes come in groups of four. example: border-color: #356 #556c80 #556c80 #356;. I have designed these functions to replace all of the colors that need replacing with the desired color type and return a copy of the original string with only the colors changed.

 

*AnimTree
*Tabs
*GlideMenus
*DragLib