颜色值判断
/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test('#009a61')
/^rgb/.test('rgb(0, 154, 97)')
/^hsl/.test('hsl(0, 0%, 20%)')
HEX颜色值转换为RGB
// Colors
function hexToRgb(hexValue) {
const rgx = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
const hex = hexValue.replace(rgx, (m, r, g, b) => r + r + g + g + b + b );
const rgb = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
const r = parseInt(rgb[1], 16);
const g = parseInt(rgb[2], 16);
const b = parseInt(rgb[3], 16);
return `rgb(${r},${g},${b})`;
}
HSL颜色值转换为RGB
HSL 为 色相,饱和度,亮度。
function hslToRgb(hslValue) {
const hsl = /hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.exec(hslValue);
const h = parseInt(hsl[1]) / 360;
const s = parseInt(hsl[2]) / 100;
const l = parseInt(hsl[3]) / 100;
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;
}
let r, g, b;
if (s == 0) {
r = g = b = l;
} else {
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 `rgb(${r * 255},${g * 255},${b * 255})`;
}