About This Product
FontsMadeEasy.com
 
Search This Database:
| Over 5000 Free Fonts | Tutorials | Javascript Forum | Other Javascript Resources | Cheat Sheet
Tutorial archive
General Questions
Javascript 1.2
Navigation
Numbers
Strings
Object Model
Reference Manual
Dialog
Windows
Frames
Forms
Images
Mouse Events
Colors
File Access
Control Status Bar
Dates and Time
Cookies
Client Information
Bookmarklets


RGB-to-Hex Conversion

Question: How do I convert RGB values of a color to a hexadecimal string?

Answer: 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 does this conversion:

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);
}
Try it yourself:
R: G: B:

BackBack