Random colors and patterns
by Adam Granger
HTML
<div id="light">
</div>
CSS
#light {
width:200px;
height:200px;
border: 1px solid black;
}
JavaScript
function Pattern() {
this.clock = 0;
this.divider = 16;
}
Pattern.prototype.next = function() {
this.clock++;
};
Pattern.prototype.getColor = function() {
return [0, 0, 0];
};
/**
* random color each time asked
*/
function RandomPattern() {
}
RandomPattern.prototype = new Pattern();
RandomPattern.prototype.getColor = function() {
return [Math.random() * 255,
Math.random() * 255,
Math.random() * 255];
};
/**
* Move through list of patterns.
*/
function PatternSeq(patterns) {
this.patterns = patterns;
this.pattern = patterns[0];
}
PatternSeq.prototype = new Pattern();
PatternSeq.prototype.next = function() {
Pattern.prototype.next.call(this);
var ind = Math.floor(this.clock / this.divider) % this.patterns.length;
this.pattern = this.patterns[ind];
this.pattern.next();
};
PatternSeq.prototype.getColor = function() {
return this.pattern.getColor();
};
/**
* fade between colors.
* @param colors list of colors (array of 3-tuples))
*/
function FadePattern(colors) {
this.colors = colors;
}
FadePattern.prototype = new Pattern();
FadePattern.prototype.getColor = function() {
var d = Math.floor(this.clock / this.divider);
var thisColor = this.colors[d % this.colors.length];
var nextColor = this.colors[(d+ 1) % this.colors.length];
var thisHsl = rgbToHsl(thisColor[0], thisColor[1], thisColor[2]);
var nextHsl = rgbToHsl(nextColor[0], nextColor[1], nextColor[2]);
var dh = (nextHsl[0] - thisHsl[0]) / this.divider;
var ds = (nextHsl[1] - thisHsl[1]) / this.divider;
var dl = (nextHsl[2] - thisHsl[2]) / this.divider;
var step = this.clock % this.divider;
var midHsl = [colorWrap(thisHsl[0] + dh * step),
colorWrap(thisHsl[1] + ds * step),
colorWrap(thisHsl[2] + dl * step)];
var midRgb = hslToRgb(midHsl[0], midHsl[1], midHsl[2]);
return midRgb;
};
/**
* Just a solid color
* @param color
*/
function...