感觉我在这里遗漏了一些非常简单的东西,但我无法从HSL to RGB color conversion的答案中找到公式。有问题的功能是:
function hslToRgb(h, s, l){
var r, g, b;
if(s == 0){
r = g = b = l; // achromatic
}else{
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;
}
var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
var p = 2 * l - q;
r = hue2rgb(p, q, h + 1/3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1/3);
}
return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
}
我认为,我的问题是关于什么进入我的&#39; h&#39;参数。通常,在CSS或Photoshop中使用HSL时,色调值是介于0和360之间的数字,但此函数需要介于0和1之间的值。有人可以向我解释我将如何转换色调值240到0到1之间的等价值,所以我可以把它插入这个公式?我尝试将240除以360,但这不起作用。
答案 0 :(得分:3)
看起来原始算法是错误的。根据{{3}},您可以获得色度和色度。亮度调整独立于色调(因此类似的b值),但其他任何东西都需要更多的数学特定模数。看起来该算法不能很好地处理特定转换,特别是考虑到它希望色调在[0,1]范围内。请尝试使用此算法:
// expected hue range: [0, 360)
// expected saturation range: [0, 1]
// expected lightness range: [0, 1]
var hslToRgb = function(hue, saturation, lightness){
// based on algorithm from http://en.wikipedia.org/wiki/HSL_and_HSV#Converting_to_RGB
if( hue == undefined ){
return [0, 0, 0];
}
var chroma = (1 - Math.abs((2 * lightness) - 1)) * saturation;
var huePrime = hue / 60;
var secondComponent = chroma * (1 - Math.abs((huePrime % 2) - 1));
huePrime = Math.floor(huePrime);
var red;
var green;
var blue;
if( huePrime === 0 ){
red = chroma;
green = secondComponent;
blue = 0;
}else if( huePrime === 1 ){
red = secondComponent;
green = chroma;
blue = 0;
}else if( huePrime === 2 ){
red = 0;
green = chroma;
blue = secondComponent;
}else if( huePrime === 3 ){
red = 0;
green = secondComponent;
blue = chroma;
}else if( huePrime === 4 ){
red = secondComponent;
green = 0;
blue = chroma;
}else if( huePrime === 5 ){
red = chroma;
green = 0;
blue = secondComponent;
}
var lightnessAdjustment = lightness - (chroma / 2);
red += lightnessAdjustment;
green += lightnessAdjustment;
blue += lightnessAdjustment;
return [Math.round(red * 255), Math.round(green * 255), Math.round(blue * 255)];
};
在一些边缘情况下可能会失败,但那些应该很容易修复