Skip to content

Commit

Permalink
Create hex转换成rgba格式 - hex2rgba.js
Browse files Browse the repository at this point in the history
  • Loading branch information
Rain120 authored Apr 2, 2019
1 parent 2a315e1 commit c2e6241
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions hex转换成rgba格式 - hex2rgba.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/*
* hex -> rgba
* #ff00ff -> rgba(255, 0, 255, 1)
*/

function hex2rgba(hex, opacity = 1) {
let color;
if (/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)) {
color = hex.substring(1).split('');
if (color.length === 3) {
color= [color[0], color[0], color[1], color[1], color[2], color[2]];
}
color = '0x' + color.join('');
return 'rgba(' + [(color >> 16) & 255, (color >> 8) & 255, color & 255].join(', ') + `, ${opacity})`;
}
throw new Error('Bad Hex');
}

hex2rgba('#ef45ae', 0.5);

0 comments on commit c2e6241

Please sign in to comment.