Last active
April 4, 2019 07:34
-
-
Save LI-NA/728af23d1cd323f72294c4c991620796 to your computer and use it in GitHub Desktop.
How to convert HEX. RGB, RGBA... etc
This file contains hidden or 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
// One line HEX to RGB. Super fast and human-readable (maybe?) | |
let hex = "#aabbcc"; | |
console.log("Simple one line HEX to RGB", "rgb(" + ['0x' + hex[1] + hex[2] | 0, '0x' + hex[3] + hex[4] | 0, '0x' + hex[5] + hex[6] | 0].join() + ")"); | |
// It can be make like this to support RGBA. | |
let hex1 = "#aabbccdd"; | |
console.log("Simple one line HEX to RGB", "rgba(" + ['0x' + hex1[1] + hex1[2] | 0, '0x' + hex1[3] + hex1[4] | 0, '0x' + hex1[5] + hex1[6] | 0, (hex1[7] ? ('0x' + hex1[7] + hex1[8] | 0) / 255 : 0)].join() + ")"); | |
// To make function... (support #abc, #aabbcc, #aabbccdd) | |
const hexToRgb = function (hex) { | |
if (hex.length == 4) return "rgb(" + ['0x' + hex[1] + hex[1] | 0, '0x' + hex[2] + hex[2] | 0, '0x' + hex[3] + hex[3] | 0].join() + ")"; | |
else if (hex.length == 7) return "rgb(" + ['0x' + hex[1] + hex[2] | 0, '0x' + hex[3] + hex[4] | 0, '0x' + hex[5] + hex[6] | 0].join() + ")"; | |
else if (hex.length == 9) return "rgba(" + ['0x' + hex[1] + hex[2] | 0, '0x' + hex[3] + hex[4] | 0, '0x' + hex[5] + hex[6] | 0, (hex[7] ? ('0x' + hex[7] + hex[8] | 0) / 255 : 0)].join() + ")"; | |
} | |
let hex2 = "#abc"; | |
console.log("Support short hex", hexToRgb(hex2)); | |
// RGB to HEX... Support RGBA | |
const rgbToHex = function (rgb) { | |
// Parse to Array | |
rgb = rgb.replace(/(rgb(a?)\(|\))/g, "").split(",").map(v => Number(v)); | |
// 0~1 to 0~255. Is there any better solution for this? | |
if (rgb[3]) rgb[3] = Math.floor(rgb[3] * 255); | |
// Make Hex. | |
return "#" + rgb.map(v => v.toString(16).padStart(2, "0")).join(""); | |
// You can upper. return "#" + rgb.map(v => v.toString(16).padStart(2, "0")).join("").toUpperCase(); | |
} | |
let rgb = "rgb(170,187,204)"; | |
let rgba = "rgba(170,187,204, .87)"; | |
console.log("RGB to HEX", rgbToHex(rgb)); | |
console.log("RGBA to HEX", rgbToHex(rgba)); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How does it works:
You may know, string is Array, so convert #AABBCC to 0xAA using hex[1], hex[2].
And if you use "0xAA" | 0, it will return number because javascript cast string to number automatically.
If you want, you can use parseInt(hex[1] + hex[2], 16). It will be work same as '0x' + hex[1] + hex[2] | 0.
Thats it.