75 lines
1.4 KiB
JavaScript
75 lines
1.4 KiB
JavaScript
function fillPartialHSL(newcolor, oldcolor) {
|
|
//console.log(newcolor, oldcolor);
|
|
let color = {};
|
|
color.hue = (newcolor.hue != null) ? newcolor.hue : oldcolor.hue;
|
|
color.sat = (newcolor.sat != null) ? newcolor.sat : oldcolor.sat;
|
|
color.l = (newcolor.l != null) ? newcolor.l : oldcolor.l;
|
|
return color;
|
|
}
|
|
|
|
function clamp(value, min, max) {
|
|
return Math.min(max, Math.max(min, value));
|
|
}
|
|
|
|
function HSL_to_RGB(hsl) {
|
|
let h = hsl.hue / 360;
|
|
let s = hsl.sat / 100;
|
|
let l = hsl.l / 100;
|
|
|
|
let r, g, b;
|
|
|
|
if (s == 0) {
|
|
r = g = b = l; // achromatic
|
|
} else {
|
|
let q = l < 0.5 ? l * (1 + s) : l + s - l * s;
|
|
let p = 2 * l - q;
|
|
|
|
r = hue2rgb(p, q, h + 1/3);
|
|
g = hue2rgb(p, q, h);
|
|
b = hue2rgb(p, q, h - 1/3);
|
|
}
|
|
|
|
return {
|
|
red: Math.round(r * 255),
|
|
green: Math.round(g * 255),
|
|
blue: Math.round(b * 255)
|
|
};
|
|
}
|
|
|
|
function RGB_to_HSL(rgb) {
|
|
let r = rgb.red / 255;
|
|
let g = rgb.green / 255;
|
|
let b = rgb.blue / 255;
|
|
|
|
let max = Math.max(r, g, b), min = Math.min(r, g, b);
|
|
|
|
if (max == min || max - min < 0.01) {
|
|
h = s = 0; // achromatic
|
|
} else {
|
|
var d = max - min;
|
|
s = d / (2 - 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;
|
|
}
|
|
|
|
let l = 1 - 0.5 * s;
|
|
|
|
return {
|
|
hue: Math.round(h * 360),
|
|
sat: Math.round(s * 100),
|
|
l: Math.round(l * 100)
|
|
};
|
|
}
|
|
|
|
module.exports = {
|
|
fillPartialHSL,
|
|
clamp,
|
|
HSL_to_RGB,
|
|
RGB_to_HSL,
|
|
}; |