HTML and CSS Reference
In-Depth Information
This is the value 0x55. With blue, you don't need to shift anything. Just AND it with 0xFF, which preserves
the blue and knocks out the red and green. This returns the value 0xF3.
Transparency
If you want to apply a color with transparency to the canvas element, you must use a string formatted in
the CSS-style functional notation: " rgba(R, G, B, A)" . In this format, the red-green-blue components
are integer values in the range of 0-255, whereas the alpha component is a decimal number in the range
of 0-1. An alpha value of 0 is completely transparent, whereas a value of 1 indicates a color that is fully
visible. For example, a color containing an alpha value of 0.5 has 50% opacity.
If you work with separate color components, you must concatenate them into a properly formatted string to
use the color with the canvas element. For example:
var r = 0xFF,
g = 0x55,
b = 0xF3,
a = 0.2,
color = "rgba(" + r + "," + g + "," + b + "," + a + ")";
console.log(color);
This assembles and prints the string: " rgba(255,85,243,0.2)" , which represents a light-purple color, at
20% visibility, properly formatted to use with the canvas element.
Because these types of conversions are rather bothersome, we create a couple of utility functions to
simplify this process in the next section.
Color utility functions
Now that we explained the process of combining and extracting color components, we create a pair of
utility functions to do the work for us. This gives us a succinct way to convert color values from numbers to
strings, and back again, while keeping the sample code uncluttered. Often when animating the canvas
element, you need to manipulate the numeric color values using JavaScript, then format them as a CSS-
style string.
The first utility function, utils.colorToRGB , takes a color value as an argument—as a number or
hexadecimal string—and extracts its individual red, blue, and green components. Then, it concatenates
them into a CSS-style string using the functional notation, which it returns. Additionally, the function
accepts a second, optional, argument to indicate an alpha value, which is a decimal number between 0
and 1.
For example, passing the hexadecimal number 0xFFFF00 or string "#FFFF00" to utils.colorToRGB
returns a string value: "rgb(255,255,0)" . If we call it with an alpha value like
utils.colorToRGB(0xFFFF00, 0.5) , it returns "rgba(255,255,0,0.5)" , which is the format that the
canvas element is looking for.
 
Search WWH ::




Custom Search