如截图,输入文字颜色色值,函数自动处理,输出背景色。
颜色方向:饱和度更低,明度更高
处理思路:十六进制的色值,前两位代表红色,3-4为代表绿色,最后2位代表蓝色。是处理后的RGB模式色值。
具体方法
// 获取更浅颜色
setTheme() {
// const lighterColor = this.lighten(处理前的色值, 降低的饱和度, 增加的明度);
const lighterColor = this.lighten(409EFF, 0.5, 0.3);
},
调整颜色的方法
// 调整颜色
lighten(hex, saturationDecrease, lightnessDecrease) {
// 解析十六进制颜色值
const r = parseInt(hex.substring(1, 3), 16);
const g = parseInt(hex.substring(3, 5), 16);
const b = parseInt(hex.substring(5, 7), 16);
// 转换为 HSL 格式
let hslColor = this.rgbToHsl(r, g, b);
// 减少饱和度和明度
hslColor[1] = Math.max(0, hslColor[1] - saturationDecrease);
hslColor[2] = Math.max(0, hslColor[2] + lightnessDecrease);
// 转换回 RGB 格式
let rgbColor = this.hslToRgb(hslColor[0], hslColor[1], hslColor[2]);
// 转换为十六进制颜色值
const darkenedHex = this.rgbToHex(rgbColor[0], rgbColor[1], rgbColor[2]);
return darkenedHex;
},
颜色的转换
// 将 RGB 颜色值转换为 HSL 格式
rgbToHsl(r, g, b) {
(r /= 255), (g /= 255), (b /= 255);
const max = Math.max(r, g, b),
min = Math.min(r, g, b);
let h,
s,
l = (max + min) / 2;
if (max === min) {
h = s = 0; // achromatic
} else {
const d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch (max) {
case r:
h = (g - b) / d + (g < b ? 6 : 0);
break;
case g:
h = (b - r) / d + 2;
break;
case b:
h = (r - g) / d + 4;
break;
}
h /= 6;
}
return [h, s, l];
},
// 将 HSL 颜色值转换为 RGB 格式
hslToRgb(h, s, l) {
let r, g, b;
if (s === 0) {
r = g = b = l; // achromatic
} else {
const hue2rgb = function hue2rgb(p, q, t) {
if (t < 0) t += 1;
if (t > 1) t -= 1;
if (t < 1 / 6) return p + (q - p) * 6 * t;
if (t < 1 / 2) return q;
if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
return p;
};
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
const p = 2 * l - q;
r = hue2rgb(p, q, h + 1 / 3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1 / 3);
}
return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
},
// 将 RGB 颜色值转换为十六进制格式
rgbToHex(r, g, b) {
return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
},