Why doesn't this Javascript RGB to HSL code work?

前端 未结 4 1054
独厮守ぢ
独厮守ぢ 2020-11-27 07:31

I found this RGB to HSL script over at http://www.mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript. I can\'t find any other s

4条回答
  •  眼角桃花
    2020-11-27 08:01

    Short but precise

    It looks that your code is ok (but it returns hue=0.24 - multiply this by 360 degree to get angle integer value) - however Try this shorter one ( more: hsl2rgb, rgb2hsv, hsv2rgb and sl22sv):

    // in: r,g,b in [0,1], out: h in [0,360) and s,l in [0,1]
    function rgb2hsl(r,g,b) {
      let v=Math.max(r,g,b), c=v-Math.min(r,g,b), f=(1-Math.abs(v+v-c-1)); 
      let h= c && ((v==r) ? (g-b)/c : ((v==g) ? 2+(b-r)/c : 4+(r-g)/c)); 
      return [60*(h<0?h+6:h), f ? c/f : 0, (v+v-c)/2];
    }
    

    function rgb2hsl(r,g,b) {
      let v=Math.max(r,g,b), c=v-Math.min(r,g,b), f=(1-Math.abs(v+v-c-1)); 
      let h= c && ((v==r) ? (g-b)/c : ((v==g) ? 2+(b-r)/c : 4+(r-g)/c)); 
      return [60*(h<0?h+6:h), f ? c/f : 0, (v+v-c)/2];
    }
    
    console.log(`rgb: (0.36,0.3,0.24) --> hsl: (${rgb2hsl(0.36,0.3,0.24)})`);
    
    
    // ---------------
    // UX
    // ---------------
    
    rgb= [0,0,0];
    hs= [0,0,0];
    
    let $ = x => document.querySelector(x);
    
    let hsl2rgb = (h,s,l, a=s*Math.min(l,1-l), f= (n,k=(n+h/30)%12) => l - a*Math.max(Math.min(k-3,9-k,1),-1)) => [f(0),f(8),f(4)];
    
    function changeRGB(i,e) {
      rgb[i]=e.target.value/255;
      hs = rgb2hsl(...rgb);
      refresh();
    }
    
    function changeHS(i,e) {
      hs[i]=e.target.value/(i?255:1);
      rgb= hsl2rgb(...hs);
      refresh();
    }
    
    function refresh() {
      rr = rgb.map(x=>x*255|0).join(', ')
      tr = `RGB: ${rr}`
      th = `HSL: ${hs.map((x,i)=>i? (x*100).toFixed(2)+'%':x|0).join(', ')}`
      $('.box').style.backgroundColor=`rgb(${rr})`;  
      $('.infoRGB').innerHTML=`${tr}`;  
      $('.infoHS').innerHTML =`${th}`;  
      
      $('#r').value=rgb[0]*255;
      $('#g').value=rgb[1]*255;
      $('#b').value=rgb[2]*255;
      
      $('#h').value=hs[0];
      $('#s').value=hs[1]*255;
      $('#l').value=hs[2]*255;  
    }
    
    refresh();
    .box {
      width: 50px;
      height: 50px;
      margin: 20px;
    }
    
    body {
        display: flex;
    }
    R
    G
    B
    
    
    H
    S
    L

    I develop S_HSL wiki formulas (marked by green border) - where MAX=max(r,g,b) and MIN=min(r,g,b) - and in above code I make some improvements and make analysis which shows that results are correct. This allows me to get quite short code at the end

提交回复
热议问题