HSL to RGB color conversion

后端 未结 21 2704
忘了有多久
忘了有多久 2020-11-22 01:59

I am looking for a JavaScript / PHP algorithm to convert between HSL color to RGB.

It seems to me that HSL is not very widely used so I am not having much luck search

21条回答
  •  粉色の甜心
    2020-11-22 02:31

    This is how I do it which is easy to remember is to think of RGB as three spokes on a wheel, 120 degrees apart.

    H = hue (0-360)
    S = saturation (0-1)
    L = luminance (0-1)
    
    R1 = SIN( H ) * L 
    G1 = SIN( H + 120 ) * L 
    B1 = SIN( H + 240 ) * L 
    

    The tricky part is saturation, which is to a scale down to the average of those three.

    AVERAGE = (R1 + G1 + B1) / 3 
    
    R2 = ((R1 - AVERAGE) * S) + AVERAGE 
    G2 = ((G1 - AVERAGE) * S) + AVERAGE 
    B2 = ((B1 - AVERAGE) * S) + AVERAGE 
    
    RED = R2 * 255 
    GREEN = G2 * 255 
    BLUE = B2 * 255 
    

提交回复
热议问题