index.js
27 lines
| 1 | /** |
| 2 | * Turn hex values to RGBA. |
| 3 | * |
| 4 | * @param {string} hex the color hex. |
| 5 | * @param {number} alpha the alpha number. |
| 6 | * @return {string} rgba color. |
| 7 | */ |
| 8 | export default function hexToRGBA( hex, alpha ) { |
| 9 | if ( ! hex ) { |
| 10 | return ''; |
| 11 | } |
| 12 | |
| 13 | if ( ! alpha && 0 !== alpha ) { |
| 14 | return hex; |
| 15 | } |
| 16 | |
| 17 | if ( 1 === alpha || ! hex.startsWith( '#' ) ) { |
| 18 | return hex; |
| 19 | } |
| 20 | |
| 21 | hex = hex.replace( '#', '' ); |
| 22 | const r = parseInt( hex.length === 3 ? hex.slice( 0, 1 ).repeat( 2 ) : hex.slice( 0, 2 ), 16 ); |
| 23 | const g = parseInt( hex.length === 3 ? hex.slice( 1, 2 ).repeat( 2 ) : hex.slice( 2, 4 ), 16 ); |
| 24 | const b = parseInt( hex.length === 3 ? hex.slice( 2, 3 ).repeat( 2 ) : hex.slice( 4, 6 ), 16 ); |
| 25 | return 'rgba(' + r + ', ' + g + ', ' + b + ', ' + alpha + ')'; |
| 26 | } |
| 27 |