HSL to RGB color conversion

后端 未结 21 2706
忘了有多久
忘了有多久 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:15

    Here is the modified javascript function, it outputs Hue in set 0-360 degrees.

    function rgbToHsl(r, g, b) {
          r /= 255, g /= 255, b /= 255;
          var max = Math.max(r, g, b), min = Math.min(r, g, b);
          var h, s, l = (max + min) / 2;
    
          if(max == min){
              h = s = 0; // achromatic
          } else {
              var d = max - min;
              s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
              switch(max){
                  case r: h = (g - b) / d ; break;
                  case g: h = 2 + ( (b - r) / d); break;
                  case b: h = 4 + ( (r - g) / d); break;
              }
              h*=60;
              if (h < 0) h +=360;
          }
         return([h, s, l]);
      }  
    alert(rgbToHsl(125,115,145));
    

提交回复
热议问题