-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.js
56 lines (48 loc) · 1.56 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/**
* rgb2hex
*
* @author Christian Bromann <[email protected]>
* @description converts rgba color to HEX
*
* @param {String} color rgb or rgba color
* @return {Object} object with hex and alpha value
*/
var rgb2hex = module.exports = function rgb2hex(color) {
if(typeof color !== 'string') {
// throw error of input isn't typeof string
throw new Error('color has to be type of `string`');
} else if (color.substr(0, 1) === '#') {
// or return if already rgb color
return {
hex: color,
alpha: 1
};
}
/**
* strip spaces
*/
var strippedColor = color.replace(/\s+/g,'');
/**
* parse input
*/
var digits = /(.*?)rgb(a)??\((\d{1,3}),(\d{1,3}),(\d{1,3})(,([01]|1.0*|0??\.([0-9]{0,})))??\)/.exec(strippedColor);
if(!digits) {
// or throw error if input isn't a valid rgb(a) color
throw new Error('given color (' + color + ') isn\'t a valid rgb or rgba color');
}
var red = parseInt(digits[3], 10);
var green = parseInt(digits[4], 10);
var blue = parseInt(digits[5], 10);
var alpha = digits[6] ? /([0-9\.]+)/.exec(digits[6])[0] : '1';
var rgb = ((blue | green << 8 | red << 16) | 1 << 24).toString(16).slice(1);
// parse alpha value into float
if(alpha.substr(0,1) === '.') {
alpha = parseFloat('0' + alpha);
}
// cut alpha value after 2 digits after comma
alpha = parseFloat(Math.round(alpha * 100)) / 100;
return {
hex: '#' + rgb.toString(16),
alpha: alpha
};
};