2016-11-15 53 views
3

我希望能夠調用一個採用基本顏色並返回對應於相同顏色的不同陰影的值的數組。該數組可以包含十六進制值或rgba()值。我希望能夠輸入所需的色調數量。陰影的數量也可以用作度量來增加陰影。例如,如果我希望輸出具有3種不同的色調,第一種色調將是基準的1/3。但是,這個數學運算將會起作用...此外,在某些情況下,第一種色調可能需要100%透明,所以我想要接受初始alpha的一個參數。我已經組織了我認爲是該功能的基本邏輯,但數學對我來說還不清楚。Javascript - 生成相同顏色的不同陰影

 var buildColorStops = function (baseColor,numberOfValues,initialAlpha) { 
      var b = baseColor; 
      var n = numberOfValues //expected number of colors in the output. If n was 3 results would be [light blue, blue(base), dark blue] (# or rgba will work) 
      var d = 1/n; // if number of values was 5 d would represent 1/5 of the base. 
      var ia = initialAlpha; // some situations may require the first color to be 100% transparent 

      var outputArray = []; 
      var i = 0; 
      while (i < n) { 
       if (i == 0) { 
        //...math on base color & incorporate initial alpha 
        outputArray.push("result of math on base") 
       } 
       else { 
        //...math on base color by incrementing d or 1/n 
        outputArray.push("result of math on base") 
       } 
      } 

      return outputArray; 
     }// end of buildColorStops 
+0

您是否搜索? http://stackoverflow.com/questions/5560248/programmatically-lighten-or-darken-a-hex-color-or-rgb-and-blend-colors – epascarello

+0

你可以添加一些例子嗎? –

+0

您也可以簡單地通過操縱數字來改變hsl,並從中生成CSS字符串 –

回答

6

通過保持顏色的比例相同,可以生成陰影。假設您的基本顏色有(r,g,b)紅色,綠色和藍色值。

所以組件之間的比例是r:g:b。如果你想生成10個陰影,那麼你的陰影將會是。

(r/10, g/10, b/10) 
(2*r/10, 2*g/10, 2*b/10) 
(3*r/10, 3*g/10, 3*b/10) 
(4*r/10, 4*g/10, 4*b/10) and so on 

這是暗色調。

較輕色調

(11*r/10, 11*g/10, 11*b/10) 
(12*r/10, 12*g/10, 12*b/10) 
(13*r/10, 13*g/10, 13*b/10) and so on 

檢查所得的R,G,B爲不超過255作爲減輕他們增加了它們的值的值。

實際上,爲了避免超過255,可以檢查r,g,b中的哪一個是最大值,並使用該值生成陰影。

var max = Math.max(r,Math.max(g,b)); 

var step = 255/(max * 10) 
(r * step, g * step, b * step) 
(r * step * 2, g * step * 2, b * step * 2) 
(r * step * 3, g * step * 3, b * step * 3) 
+0

愛這個簡單和優雅!謝謝! – LCaraway

+0

不客氣! – 11thdimension

+0

你是男人! –