|
HTML Tag and Attribute Reference
|
Convert RGB values of a color to a hexadecimal string
Here is a script that converts RGB to Hex:
<script language="JavaScript" type="text/javascript">
<!--
function RGBtoHex(R,G,B) {return toHex(R)+toHex(G)+toHex(B)}
function toHex(N) {
if (N==null) return "00";
N=parseInt(N); if (N==0 || isNaN(N)) return "00";
N=Math.max(0,N); N=Math.min(N,255); N=Math.round(N);
return "0123456789ABCDEF".charAt((N-N%16)/16)
+ "0123456789ABCDEF".charAt(N%16);
}
//-->
</script>
The algorithm is as follows:
make sure that RGB values are in the range 0...255,
convert RGB values to hex strings,
and then merge the three strings.
Here is a script that converts Hex to RGB:
<script language="JavaScript" type="text/javascript">
<!--
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}
//-->
</script>
|