silphius/app/util/color.js
2024-08-01 00:39:54 -05:00

62 lines
1.4 KiB
JavaScript

const {min, max, round} = Math;
export function hslToHex(h, s, l) {
const [r, g, b] = hslToRgb(h, s, l);
return (r << 16) | (g << 8) | b;
}
export function hslToRgb(h, s, l) {
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 = hueToRgb(p, q, h + 1/3);
g = hueToRgb(p, q, h);
b = hueToRgb(p, q, h - 1/3);
}
return [round(r * 255), round(g * 255), round(b * 255)];
}
function hueToRgb(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;
}
export function hexToHsl(i) {
const [r, g, b] = hexToRgb(i);
return rgbToHsl(r, g, b);
}
export function hexToRgb(i) {
const o = i > 16777215 ? 8 : 0;
return [
(i >> o + 16) & 255,
(i >> o + 8 ) & 255,
(i >> o + 0 ) & 255,
];
}
export function rgbToHsl(r, g, b) {
(r /= 255), (g /= 255), (b /= 255);
const vmax = max(r, g, b), vmin = min(r, g, b);
let h, s, l = (vmax + vmin) / 2;
if (vmax === vmin) {
return [0, 0, l];
}
const d = vmax - vmin;
s = l > 0.5 ? d / (2 - vmax - vmin) : d / (vmax + vmin);
if (vmax === r) h = (g - b) / d + (g < b ? 6 : 0);
if (vmax === g) h = (b - r) / d + 2;
if (vmax === b) h = (r - g) / d + 4;
h /= 6;
return [h, s, l];
}