Gradient //JavaScript Repository

Description

Given the initial and final colors and the amount of steps that the gradient effect will take, the class is able to retrieve the color that should be used on each step.
Created: 2008.03.14

Code (Download)

//+ Carlos R. L. Rodrigues
//@ http://jsfromhell.com/classes/gradient [rev. #0]

Gradient = function(i, e, t){
    var o = this;
    o.i = i, o.e = e, o.t = --t, o._ = 0, o.a = [];
    o.fix = function(v){return v.length < 2 ? "0" + v : v;}
    for(var x, j = 0; j < 3; j++)
        o.a[j] = [((e >> (j << 3) & 0xff) - (x = (i >> (j << 3) & 0xff))) / t, x];
};
Gradient.prototype.getColorAt = function(a){
    for(var o = this, a = a > o.t ? o.t : a < 0 ? 0 : a, s = "", i = 0; i < 3; i++)
        s = o.fix((o.a[i][1] + o.a[i][0] * a >> 0).toString(16)) + s;
    return s;
};
Gradient.prototype.next = function(){
    var o = this;
    return o.t >= o._ && o.getColorAt(o._++);
};
Gradient.prototype.reset = function(){
    this._ = 0;
};

Example (Example)

<style type="text/css">
    .grad{font-size:1px;} /*IE*/
</style>
<script type="text/javascript">
//<![CDATA[

var g = new Gradient(0xff0000, 0x0, 256),
d = document, f = d.createDocumentFragment(),
line = d.createElement("div");
line.className = "grad";
line.style.height = "3px";

for(var color; color = g.next();)
    f.appendChild(line.cloneNode(false)).style.background = "#" + color;

d.body.appendChild(f);

//]]>
</script>

Help

Constructor

Gradient(start: Number, final: Number, steps: Number)
Generates an instance of Gradient.
start
start color
final
final color
steps
amount of steps for the effect

Methods

Gradient.getColorAt(step: Number): String
Retrieves the color at the given step in hexadecimal.
step
desired step, the maximum value is the "steps" argument of the constructor - 1
Gradient.next(void): Object
Increments the current step of the class and retrieves the color as String, or false when it reachs the end.
Gradient.reset(void): void
Resets the current step of the class.

Rank (Votes: 23)

2.35