Skip to content

Instantly share code, notes, and snippets.

@xckevin
Created October 9, 2024 11:32
Show Gist options
  • Select an option

  • Save xckevin/afeb635e00c9a7b2f48b8a161a3a38f7 to your computer and use it in GitHub Desktop.

Select an option

Save xckevin/afeb635e00c9a7b2f48b8a161a3a38f7 to your computer and use it in GitHub Desktop.
color converter: rgb 2 HSL, hex 2 rgb
class ColorConverter {
// Hex to RGB
static hexToRgb(hex) {
let cleanHex = hex.replace('#', '');
if (cleanHex.length === 3) {
cleanHex = cleanHex.split('').map(char => char + char).join('');
}
const bigint = parseInt(cleanHex, 16);
const r = (bigint >> 16) & 255;
const g = (bigint >> 8) & 255;
const b = bigint & 255;
return `rgb(${r}, ${g}, ${b})`;
}
// Hex to RGBA
static hexToRgba(hex, alpha = 1) {
const rgb = this.hexToRgb(hex);
return rgb.replace('rgb', 'rgba').replace(')', `, ${alpha})`);
}
// RGB to Hex
static rgbToHex(r, g, b) {
const toHex = (val) => val.toString(16).padStart(2, '0');
return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
}
// RGBA to Hex
static rgbaToHex(r, g, b, a = 1) {
const alpha = Math.round(a * 255);
return this.rgbToHex(r, g, b) + alpha.toString(16).padStart(2, '0');
}
// ARGB to Hex
static argbToHex(a, r, g, b) {
const toHex = (val) => val.toString(16).padStart(2, '0');
return `#${toHex(a)}${toHex(r)}${toHex(g)}${toHex(b)}`;
}
// RGB to HSL
static 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;
} 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 `hsl(${(h * 360).toFixed(1)}, ${(s * 100).toFixed(1)}%, ${(l * 100).toFixed(1)}%)`;
}
// HSL to RGB
static hslToRgb(h, s, l) {
s /= 100;
l /= 100;
h /= 360;
let r, g, b;
if (s === 0) {
r = g = b = l;
} else {
const 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 / 3) return q;
if (t < 1 / 2) 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 `rgb(${Math.round(r * 255)}, ${Math.round(g * 255)}, ${Math.round(b * 255)})`;
}
// HSL to HSLA
static hslToHsla(h, s, l, a = 1) {
return `hsla(${h}, ${s}%, ${l}%, ${a})`;
}
// RGB to HSLA
static rgbToHsla(r, g, b, a = 1) {
const hsl = this.rgbToHsl(r, g, b).replace('hsl', '');
return `hsla${hsl.slice(0, -1)}, ${a})`;
}
// RGB to ARGB (alpha first)
static rgbToArgb(r, g, b, a = 1) {
const alpha = Math.round(a * 255);
return this.argbToHex(alpha, r, g, b);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment