user6084053
user6084053

Reputation:

Html get color in Rgb

Well i need to do a little projet in webgl and need to pass the color from the html to the javascript, the thing is that i need that color in Rgb to working direcrly with webGl, what i need to know is if there is a way using html5 to get the color in rgb from the input.

Im doing this:

<input type="color" onchange="cor()" id="color">

the prob here is if i try to get this color he gives me the hexadecimal value, i know that via javascript with a function i can convert the hexadecimal to rgb but i need to know if there is a easier way to do this and put to work.

Upvotes: 8

Views: 7446

Answers (1)

James Donnelly
James Donnelly

Reputation: 128771

Fortunately color values in HTML5 are only valid if they're in the #XXXXXX format (meaning rgb(...) and #XXX are invalid). We can use this to our advantage as we always know exactly where the RGB positions will be in the resulting value:

#XXXXXX
#RRGGBB

To convert this to rgb(...), we simply need to strip out the # character and convert the RR, GG and BB values to decimal:

// #XXXXXX -> ["XX", "XX", "XX"]
var value = value.match(/[A-Za-z0-9]{2}/g);

// ["XX", "XX", "XX"] -> [n, n, n]
value = value.map(function(v) { return parseInt(v, 16) });

// [n, n, n] -> rgb(n,n,n)
return "rgb(" + value.join(",") + ")";

And with the beauty of JavaScript, we can do this all on one line of code:

return "rgb(" + "#FF0000".match(/[A-Za-z0-9]{2}/g).map(function(v) { return parseInt(v, 16) }).join(",") + ")";
-> "rgb(255,0,0)"

Upvotes: 11

Related Questions