This repository has been archived by the owner on Sep 5, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
color.js
73 lines (66 loc) · 1.73 KB
/
color.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/**
* @ngdoc module
* @name material.core.colorUtil
* @description
* Color Util
*/
angular
.module('material.core')
.factory('$mdColorUtil', ColorUtilFactory);
function ColorUtilFactory() {
/**
* Converts hex value to RGBA string
* @param color {string}
* @returns {string}
*/
function hexToRgba (color) {
var hex = color[ 0 ] === '#' ? color.substr(1) : color,
dig = hex.length / 3,
red = hex.substr(0, dig),
green = hex.substr(dig, dig),
blue = hex.substr(dig * 2);
if (dig === 1) {
red += red;
green += green;
blue += blue;
}
return 'rgba(' + parseInt(red, 16) + ',' + parseInt(green, 16) + ',' + parseInt(blue, 16) + ',0.1)';
}
/**
* Converts rgba value to hex string
* @param {string} color
* @returns {string}
*/
function rgbaToHex(color) {
color = color.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
var hex = (color && color.length === 4) ? "#" +
("0" + parseInt(color[1],10).toString(16)).slice(-2) +
("0" + parseInt(color[2],10).toString(16)).slice(-2) +
("0" + parseInt(color[3],10).toString(16)).slice(-2) : '';
return hex.toUpperCase();
}
/**
* Converts an RGB color to RGBA
* @param {string} color
* @returns {string}
*/
function rgbToRgba (color) {
return color.replace(')', ', 0.1)').replace('(', 'a(');
}
/**
* Converts an RGBA color to RGB
* @param {string} color
* @returns {string}
*/
function rgbaToRgb (color) {
return color
? color.replace('rgba', 'rgb').replace(/,[^),]+\)/, ')')
: 'rgb(0,0,0)';
}
return {
rgbaToHex: rgbaToHex,
hexToRgba: hexToRgba,
rgbToRgba: rgbToRgba,
rgbaToRgb: rgbaToRgb
};
}