2016-11-15 49 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

你是男人! –