HTML and CSS Reference
In-Depth Information
Remember that each component color can have a value anywhere from 0 to 255, or in hex, 0x00 to 0xFF.
Thus, the color red can be represented as 0xFF0000, which denotes full red, zero green, and zero blue.
Likewise, 0x0000FF is completely blue.
If you take the earlier mentioned example number, 16,733,683, and convert it to hex (you will see an easy
way to do that), you get 0xFF55F3. You can easily separate the components into red = FF, green = 55,
and blue = F3. Examining these values, you see that the red and blue are rather high, and green is much
lower. So you can guess that this color is purplish, which is something you can't easily determine from the
decimal value.
For any JavaScript operation that requires a number, it doesn't matter which format you use, decimal or
hex. The numbers 16733683 and 0xFF55F3 have the same value; it's just that one is more readable to us
humans. However, when working with the canvas element, you must remember to convert whichever
numeric format into a proper CSS-style string.
You might wonder how to convert between these formats. Well, converting from hex to decimal is easy—
just print the value. The console.log function in your debugging console prints to decimal for you:
console.log(0xFF55F3);
This prints 16733683 . To see the hexadecimal representation of a decimal number, use the
Number.toString method, specifying 16 as the radix:
var hex = (16733683).toString(16);
console.log(hex);
As the method name indicates, this converts the number to a string, and prints out the hexadecimal
' ff55f3' . To use that value as a CSS-style formatted string, prepend the '#' character:
var hexColor = '#' + (16733683).toString(16);
This sets hexColor to a string value of '#ff55f3' . To convert this back into a decimal number, first chop
off the '#' character at the beginning of the string using the String.slice method, then pass the
remaining string to the built-in function window.parseInt , with a radix of 16:
var color = window.parseInt(hexColor.slice(1), 16);
console.log(color);
This prints out the number 16733683 , and you can see we're right back where we started.
Combining colors
Let's say you want to combine three red, green, and blue numbers to form a valid overall color value. If
you have three variables, red , green , and blue , and each of them holds an integer value from 0 to 255,
here's the formula to do just that:
color = red << 16 | green << 8 | blue;
For example, to create the purple color value from separate components, set the red value to max, or
0xFF (decimal 255), the green component to 0x55 (decimal 85), and the blue value to 0xF3 (decimal 243):
 
Search WWH ::




Custom Search