2017-09-26 79 views
-2

你好,我試圖創建十六進制HSL轉換器功能。我知道最初我應該將HEX轉換爲RGB,然後將RGB轉換爲HSL。我已經使用了StackOverflow的一些腳本。 S和L正常工作,但H(色相)不正確。我不知道爲什麼,這裏是我的代碼:十六進制到HSL轉換javascript

toHSL: function(hex) { 
    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); 

    var r = parseInt(result[1], 16); 
    var g = parseInt(result[2], 16); 
    var b = parseInt(result[3], 16); 

    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 + (g < b ? 6 : 0); break; 
      case g: h = (b - r)/d + 2; break; 
      case b: h = (r - g)/d + 4; break; 
     } 
     h /= 6; 
    } 

    s = s*100; 
    s = Math.round(s); 
    l = l*100; 
    l = Math.round(l); 

    var colorInHSL = 'hsl(' + h + ', ' + s + '%, ' + l + '%)'; 
    $rootScope.$emit('colorChanged', {colorInHSL}); 

當輸入爲#ddffdd

然後輸出hsl(0.3333333333333333, 100%, 93%)

但應該是hsl(120, 100%, 93%)

回答

1

你忘由360

s = s*100; 
s = Math.round(s); 
l = l*100; 
l = Math.round(l); 
h = Math.round(360*h); 

var colorInHSL = 'hsl(' + h + ', ' + s + '%, ' + l + '%)'; 
乘以色相