Html get color in rgb

Well, I need to make a small project in webgl and you need to transfer the color from html to javascript, the fact is that I need this color in Rgb to work with webGl, what I need to know if there is a way to use html5 to get color in rgb with input.

I'm doing it:

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

The problem is here, if I try to get this color, it gives me a hex value, I know that through javascript using a function I can convert the hex code to rgb, but I need to know if there is an easier way to do this and get started.

+5
source share
1 answer

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

 #XXXXXX #RRGGBB 

To convert this to rgb(...) , we just need to cross out the # character and convert the values ​​of RR , GG and BB to decimal numbers:

 // #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 all this 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)" 
+5
source

Source: https://habr.com/ru/post/1247374/


All Articles