Skip to content

Commit c2e6241

Browse files
authored
Create hex转换成rgba格式 - hex2rgba.js
1 parent 2a315e1 commit c2e6241

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

hex转换成rgba格式 - hex2rgba.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
/*
2+
* hex -> rgba
3+
* #ff00ff -> rgba(255, 0, 255, 1)
4+
*/
5+
6+
function hex2rgba(hex, opacity = 1) {
7+
let color;
8+
if (/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)) {
9+
color = hex.substring(1).split('');
10+
if (color.length === 3) {
11+
color= [color[0], color[0], color[1], color[1], color[2], color[2]];
12+
}
13+
color = '0x' + color.join('');
14+
return 'rgba(' + [(color >> 16) & 255, (color >> 8) & 255, color & 255].join(', ') + `, ${opacity})`;
15+
}
16+
throw new Error('Bad Hex');
17+
}
18+
19+
hex2rgba('#ef45ae', 0.5);

0 commit comments

Comments
 (0)