在颜色的计算中,往往需要统一的标准
以下记录一些换算方法
HSV 是指☞ Hue色相、Saturation饱和度、Value明度(亮度)。
HSVtoRGB(h, s, v) {
let i, f, p1, p2, p3;
let r = 0, g = 0, b = 0;
if (s < 0) s = 0;
if (s > 1) s = 1;
if (v < 0) v = 0;
if (v > 1) v = 1;
h %= 360;
if (h < 0) h += 360;
h /= 60;
i = Math.floor(h);
f = h - i;
p1 = v * (1 - s);
p2 = v * (1 - s * f);
p3 = v * (1 - s * (1 - f));
switch(i) {
case 0: r = v; g = p3; b = p1; break;
case 1: r = p2; g = v; b = p1; break;
case 2: r = p1; g = v; b = p3; break;
case 3: r = p1; g = p2; b = v; break;
case 4: r = p3; g = p1; b = v; break;
case 5: r = v; g = p1; b = p2; break;
}
return 'rgb(' + Math.round(r * 255) + ',' + Math.round(g * 255) + ',' + Math.round(b * 255) + ')';
}
RGBtoHSV(rgb) {
rgb = this.getRGB(rgb)
var rr, gg, bb,
r = parseInt(rgb.red) / 255,
g = parseInt(rgb.green) / 255,
b = parseInt(rgb.blue) / 255,
h, s,
v = Math.max(r, g, b),
diff = v - Math.min(r, g, b),
diffc = function(c){
return (v - c) / 6 / diff + 1 / 2;
};
if (diff == 0) {
h = s = 0;
} else {
s = diff / v; rr = diffc(r); gg = diffc(g); bb = diffc(b);
if (r === v) {
h = bb - gg;
}else if (g === v) {
h = (1 / 3) + rr - bb;
}else if (b === v) {
h = (2 / 3) + gg - rr;
}
if (h < 0) {
h += 1;
}else if (h > 1) {
h -= 1;
}
}
return {
h: Math.round(h * 360),
s: Math.round(s * 100),
v: Math.round(v * 100)
};
}
通过单一的色相值也可以得到纯色的rgb值
HuetoRGB(h) {
let doHandle = (num) =>{
if( num > 255) {
return 255;
} else if(num < 0){
return 0;
} else {
return Math.round(num);
}
}
let hueRGB = h/60 * 255;
let r = doHandle(Math.abs(hueRGB-765)-255);
let g = doHandle(510 - Math.abs(hueRGB-510));
let b = doHandle(510 - Math.abs(hueRGB-1020));
return 'rgb(' +r + ',' + g + ',' + b + ')';
}
rgbArray 为
{
red: xxx,
green: xxx,
blue: xxx
}
getHue (rgbArray) {
let r, g, b, max, min;
for(let i = 0; i < 3; i++){
r = parseInt(rgbArray.red);
g = parseInt(rgbArray.green);
b = parseInt(rgbArray.blue);
}
max = Math.max(r, g, b)
min = Math.min(r, g, b)
if(max == min) {
return 0;
} else {
if( max == r && g >= b) {
return 60 * (g - b)/(max - min);
} else if ( max == r && g < b) {
return 60 * (g - b)/(max - min) + 360;
} else if (max == g) {
return 60 * (b - r)/(max - min) + 120;
} else if (max == b) {
return 60 * (r - g)/(max - min) + 240;
}
}
}
HexTorgb (hex){
var hexNum = hex.substring(1);
hexNum = '0x' + (hexNum.length < 6 ? repeatLetter(hexNum, 2) : hexNum);
var r = hexNum >> 16;
var g = hexNum >> 8 & '0xff';
var b = hexNum & '0xff';
return `rgb(${
r},${
g},${
b})`;
function repeatWord(word, num){
var result = '';
for(let i = 0; i < num; i ++){
result += word;
}
return result;
}
function repeatLetter(word, num){
var result = '';
for(let letter of word){
result += repeatWord(letter, num);
}
return result;
}
}
rgbToHex (color){
if(color.indexOf("#") != -1) {
return color;
}
let arr = color.split(',');
let r = +arr[0].split('(')[1];
let g = +arr[1];
let b = +arr[2].split(')')[0];
let value = (1 << 24) + r * (1 << 16) + g * (1 << 8) + b;
value = value.toString(16);
return '#' + value.slice(1);
}