gradientColor.js
2.97 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// 实现渐变色
export default class gradientColor {
constructor (startColor, endColor, step) {
this.startColor = startColor;
this.endColor = endColor;
this.step = step;
}
exgColor() {
var startRGB, startR, startG, startB;
startRGB = this.colorRgb(this.startColor);//转换为rgb数组模式
startR = startRGB[0];
startG = startRGB[1];
startB = startRGB[2];
var endRGB, endR, endG, endB;
endRGB = this.colorRgb(this.endColor);
endR = endRGB[0];
endG = endRGB[1];
endB = endRGB[2];
var sR, sG, sB;
sR = (endR - startR) / this.step;//总差值
sG = (endG - startG) / this.step;
sB = (endB - startB) / this.step;
var colorArr = [];
for (var i = 0; i < this.step; i++) {
//计算每一步的hex值
var hex = this.colorHex('rgb('+ parseInt((sR * i + startR))+ ',' + parseInt((sG * i + startG))+ ',' + parseInt((sB * i + startB)) + ')');
colorArr.push(hex);
}
return colorArr;
}
colorRgb (sColor) {
var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
var sColor = sColor.toLowerCase();
if (sColor && reg.test(sColor)) {
if (sColor.length === 4) {
var sColorNew = "#";
for (var i = 1; i < 4; i += 1) {
sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
}
sColor = sColorNew;
}
//处理六位的颜色值
var sColorChange = [];
for (var i = 1; i < 7; i += 2) {
sColorChange.push(parseInt("0x" + sColor.slice(i, i + 2)));
}
return sColorChange;
} else {
return sColor;
}
}
colorHex (rgb) {
var _this = rgb;
var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
if (/^(rgb|RGB)/.test(_this)) {
var aColor = _this.replace(/(?:(|)|rgb|RGB)*/g, "").split(",");
var strHex = "#";
for (var i = 0; i < aColor.length; i++) {
var hex = Number(aColor[i]).toString(16);
hex = hex < 10 ? 0 + '' + hex : hex;// 保证每个rgb的值为2位
if (hex === "0") {
hex += hex;
}
strHex += hex;
}
if (strHex.length !== 7) {
strHex = _this;
}
return strHex;
} else if (reg.test(_this)) {
var aNum = _this.replace(/#/, "").split("");
if (aNum.length === 6) {
return _this;
} else if (aNum.length === 3) {
var numHex = "#";
for (var i = 0; i < aNum.length; i += 1) {
numHex += (aNum[i] + aNum[i]);
}
return numHex;
}
} else {
return _this;
}
}
}
// export default gradientColor;