Last active
October 20, 2019 05:02
-
-
Save nitaking/6d44cbfea2ccc7f0b982d7a0c56a2282 to your computer and use it in GitHub Desktop.
hexToRgbA.js
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
// 個別にopacityを置くために | |
/** | |
ex) | |
hexToRgbA('#777777', 0.8) | |
-> "rgba(119,119,119,0.8)" | |
hexToRgbA('#777777', 0.9) | |
-> "rgba(119,119,119,0.9)" | |
hexToRgbA('#777777', 0.6) | |
-> "rgba(119,119,119,0.6)" | |
*/ | |
const hexToRgbA = (hex: string, opacity: number = 1) => { | |
let c; | |
if (/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)) { | |
c = hex.substring(1).split(''); | |
if (c.length === 3) { | |
c = [c[0], c[0], c[1], c[1], c[2], c[2]]; | |
} | |
c = `0x${c.join('')}`; | |
return `rgba(${[(c >> 16) & 255, (c >> 8) & 255, c & 255].join(',')},${opacity})`; // eslint-disable-line | |
} | |
throw new Error('Bad Hex'); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment