Created
June 6, 2018 01:16
-
-
Save comficker/871d378c535854c1c460f7867a191a5a to your computer and use it in GitHub Desktop.
Bellow are javascript code can convert hex to rgb color. Demo: http://aiconverter.com/color/hex-to-rgb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function HEX2RGB (hex) { | |
"use strict"; | |
if (hex.charAt(0) === '#') { | |
hex = hex.substr(1); | |
} | |
if ((hex.length < 2) || (hex.length > 6)) { | |
return false; | |
} | |
var values = hex.split(''), | |
r, | |
g, | |
b; | |
if (hex.length === 2) { | |
r = parseInt(values[0].toString() + values[1].toString(), 16); | |
g = r; | |
b = r; | |
} else if (hex.length === 3) { | |
r = parseInt(values[0].toString() + values[0].toString(), 16); | |
g = parseInt(values[1].toString() + values[1].toString(), 16); | |
b = parseInt(values[2].toString() + values[2].toString(), 16); | |
} else if (hex.length === 6) { | |
r = parseInt(values[0].toString() + values[1].toString(), 16); | |
g = parseInt(values[2].toString() + values[3].toString(), 16); | |
b = parseInt(values[4].toString() + values[5].toString(), 16); | |
} else { | |
return false; | |
} | |
return [r, g, b]; | |
} |
@meodai Thanks! I wasn’t aware of the context for this — the color names project looks cool. If I recall correctly, I encountered this gist because it was linked to from another site. Re: adding as a contributor — feel free, but not obligated.
@bathos meodai/color-names@cc1ea8e your in! Thanks
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@bathos Very elegant solution, I love it! I took the liberty to use it for my color-name api: meodai/color-names@bdad76b can I add you as a contributor?