Skip to content

Instantly share code, notes, and snippets.

@emrahgunduz
Created September 17, 2016 16:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emrahgunduz/f2a9a221c212b20a0bfd404f8a51aa88 to your computer and use it in GitHub Desktop.
Save emrahgunduz/f2a9a221c212b20a0bfd404f8a51aa88 to your computer and use it in GitHub Desktop.
A rainbow color generator
function generateRainbowColors(count, createDiv){
function rainbow(numOfSteps, step) {
var r, g, b;
var h = step / numOfSteps;
var i = ~~(h * 6);
var f = h * 6 - i;
var q = 1 - f;
switch(i % 6){
case 0: r = 1; g = f; b = 0; break;
case 1: r = q; g = 1; b = 0; break;
case 2: r = 0; g = 1; b = f; break;
case 3: r = 0; g = q; b = 1; break;
case 4: r = f; g = 0; b = 1; break;
case 5: r = 1; g = 0; b = q; break;
}
var c = "#" + ("00" + (~ ~(r * 255)).toString(16)).slice(-2) + ("00" + (~ ~(g * 255)).toString(16)).slice(-2) + ("00" + (~ ~(b * 255)).toString(16)).slice(-2);
return (c);
}
if(!count) count = 50;
if(!createDiv) createDiv = false;
var ww = window.innerWidth;
var w = Math.ceil(ww / 30);
var x = 0;
var y = 0;
var colors = [];
for (var i = 0; i < count; i++){
var color = rainbow(count, i);
colors.push(color);
if(createDiv) {
var div = document.createElement("div");
div.style.position = "absolute";
div.style.left = x + "px";
div.style.top = y + "px";
div.style.width = w + "px";
div.style.height = w + "px";
div.style.backgroundColor = color;
document.body.appendChild(div);
x = x + w;
if(x > ww){
x = 0;
y = y + w;
div.style.left = x + "px";
div.style.top = y + "px";
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment