Hex-to-RGB ConversionQuestion: How do I convert a hex color string (e.g. "FFFFCC") to numeric RGB values?
Answer:
The JavaScript source code is simple: R = hexToR("#FFFFFF"); G = hexToG("#FFFFFF"); B = hexToB("#FFFFFF"); function hexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)} function hexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)} function hexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)} function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}The script uses a helper function cutHex()
to check if the # character is present in the beginning of the input hexadecimal value.
If so, the cutHex() function cuts off the #
so that only the hexadecimal digits are left in the input value.
We use the standard JavaScript method
substring() to get the
R , G , B (red, green, blue) hex substrings
from the input hexadecimal value.
Finally, the script parses the R , G , B values
from hexadecimal string parseInt(string,16) ;
the second argument 16 specifies that the string must be parsed as
a hexadecimal (base-16) value.
See also:
|
Copyright © 1999-2012, JavaScripter.net.