color-fns
Version:
Modern JavaScript color utility library.
43 lines • 1.48 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
var parseRgb_1 = require("./parseRgb");
function rgbToHsl(rgb) {
rgb = typeof rgb === 'string' ? parseRgb_1.parseRgb(rgb) : rgb;
if (!rgb) {
return null;
}
// Convert the RGB values to the range 0-1
var _a = [rgb.red / 255, rgb.green / 255, rgb.blue / 255, rgb.alpha], red = _a[0], green = _a[1], blue = _a[2], alpha = _a[3];
var _b = [0, 0, 0], hue = _b[0], sat = _b[1], lum = _b[2];
// Find the minimum and maximum values of R, G and B.
var min = Math.min(red, green, blue);
var max = Math.max(red, green, blue);
// Calculate the lightness value
lum = (min + max) / 2;
// Calculate the saturation.
if (min !== max) {
sat = lum > 0.5 ? (max - min) / (2 - max - min) : (max - min) / (max + min);
}
// calculate the hue
if (red >= max && min !== max) {
hue = 60 * ((green - blue) / (max - min));
}
if (green >= max && min !== max) {
hue = 60 * (2.0 + (blue - red) / (max - min));
}
if (blue >= max && min !== max) {
hue = 60 * (4.0 + (red - green) / (max - min));
}
// normalize values
hue = hue < 0 ? Math.floor(hue + 360) : Math.floor(hue);
sat = Math.floor(sat * 100);
lum = Math.floor(lum * 100);
return {
alpha: alpha,
hue: hue,
lum: lum,
sat: sat
};
}
exports.rgbToHsl = rgbToHsl;
//# sourceMappingURL=rgbToHsl.js.map