JavaScript function to return “n” shades of a given color from (dark to light)

倾然丶 夕夏残阳落幕 提交于 2019-12-12 08:07:50

问题


I would like to get the color range of the specific color for generating tag cloud.

Say that user has entered some color with RGB/HHHHHH values then I would like to write a function f(color, no) which returns RGB/HHHHHH for "no" of different shades from dark to light colors for specified "color". These colors then will be useful to display the different tags with different color of same shade. But I would like to avoid black and white shades in it.

Following is example of F({R:0, G:0, B:255}, 7) which returns 7 shades of blue.

I would not like it to be true for any RGB combination say for example (25, 150,150) also.

Is this function possible using JavaScript or is there any formula for RGB with which this can be achieved?


回答1:


function generate()
{
  var r = document.querySelector("#R").value%256;
  var g = document.querySelector("#G").value%256;
  var b = document.querySelector("#B").value%256;
  var str="";
  for(var i=0;i<7;i++)
  {
    r+=33;
    g+=33;
    b+=33;
    str+="<div class='swatch' style='background-color:rgb("+r+","+g+","+b+")'></div>";
  }
  document.querySelector("#op").innerHTML = str;
  console.log(str);
}
.swatch{width:50px;height:25px;margin:1px}
<div>R<input type="text" id="R"/></div>
<div>G<input type="text" id="G"/></div>
<div>B<input type="text" id="B"/></div>
<input type="button" onclick="generate()" value="Generate"/>
<div id="op">Generated Color shades</div>

Do you want something like this on jsbin? This is a demo that I have built using jQuery.

Let me know if you have any doubts.




回答2:


You want to operate on saturation and value, convert rgb to hsv first and then it is very easy.

Code: http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript

Info: http://en.wikipedia.org/wiki/HSL_and_HSV



来源:https://stackoverflow.com/questions/5324359/javascript-function-to-return-n-shades-of-a-given-color-from-dark-to-light

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!