How to generate rainbow colors

Hi There,
At times you might have to generate few colors which almost covers entire rainbow (visible spectrum) range.

Here in this article I am giving away a function which generates as many colors as you want but those colors will try to cover the entire (visible light) spectrum. i.e if you just generate 3 colors you will get Green, Red and Blue. If you generate 100 colors you will get multiple tints of Green, Red and Blue.

Function Name is : getColor(count)
Input count: Number of colors to generate.
Returns : li items with color (as style attribute).

<li class="color" style="background-color:rgb(254,64,54);">  </li>

How it works?
I have taken 3 sine waves, all are with different phase. Each of these sine curve generates my RGB values. Each sine wave will swing from 0 to 2pie (360deg). There has been a bit of normalization just to make the colors look good (in final code).

function getColor(noOfColors) {
    html = "";
    frequency = 5 / noOfColors; 
    for (var i = 0; i < noOfColors;++i) {
        r = Math.sin(frequency * i + 0) * (127) + 128;
        g = Math.sin(frequency * i + 1) * (127) + 128;
        b = Math.sin(frequency * i + 3) * (127) + 128;
        li = '<li class="color" style="background-color:rgb({r},{g},{b});">  </li>';
        li = li.replace("{r}", Math.floor(r));
        li = li.replace("{g}", Math.floor(g));
        li = li.replace("{b}", Math.floor(b));
        html = html + li;
    return html;

                                                                  Demo jsfiddle 

No comments:

Post a Comment

Your comment will inspire me, Please leave your comment