In the previous article for Javascript to convert Decimal to hex, we learnt how to convert decimal numbers to hex code. Now here to RGB i.e. Red, Green, Blue value for color codes also belong to decimal number system. To convert RGB to hex code we need the same javascript hex code function that we used in the last article. But here in this sample for javascript convert RGB to Hex we need a simple hex code function that can convert decimal numbers from 0 to 255.
To generate hex code like #C0C0C0 we need user input in the form of RGB coz hex code for colors represents the combination of RGB in the form of hex code having two digits for RGB. E.g. In #C0C0C0, first pair C0 represents the hex code for Red (192), second pair C0 for Green (192) and similarly last C0 for Blue (192).
Javascript function to convert RGB to Hex asks user to input the values in the form of R, G, B. This comma separated combination of RGB can be used to convert the RGB to hex by generating hex code for each color. User can input value between 0-255 for Red, Green and Blue. E.g.: 192,192, 192 will convert this RGB value to C0C0C0.
Javascript code to convert RGB to Hex
JavaScript code
function toRGBHex(num) {
var decToHex = "";
var arr = new Array();
var numStr = new String();
numStr = num;
arr = numStr.split(",");
var hexArray = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F");
for (var i = 0; i < 3; i++) {
var code1 = Math.floor(arr[i] / 16); var code2 = arr[i] - code1 * 16;
decToHex += hexArray[code1];
decToHex += hexArray[code2];
}
return (decToHex);
}
HTML Code
<input
id="Text1"
type="text" /><br />
<input
id="Text2"
type="text" />
<input id="Button1"
type="button"
value="convert RGB to Hex code"
onclick=" document.getElementById( 'Text2' ).value = toRGBHex( document.getElementById( 'Text1' ).value );" />
In the above sample code to convert RGB to Hex toRGBHex function splits the R, G, B value entered by the user and creates an Array having RGB value at its 0, 1 and 2 indexes. The for loop generates the hex value for RGB value stored at each index of Array and returns the concatenated result of RGB Hex code of color.
Continue to next tutorial: JavaScript Random Numbers to learn how to generate random numbers using random method.