To scale a color correctly, you have to multiply each RGB value by a proportion. E.g.
, if your color is #00417b
and you want a color that is 125% lighter color then you have to do this:
var dark = {r: 0, g: 65, b: 123};
var light = {r: Math.round(Math.min(dark[r]*1.25, 255)),
g: Math.round(Math.min(dark[g]*1.25, 255)),
b: Math.round(Math.min(dark[b]*1.25, 255))};
Compare the result for yourself: dark is #00417b
, and light is #00519A
, although it's perfectly valid CSS to describe them as rgb(0, 65, 123)
and rgb(0, 81, 154)
and probably easier too. By scaling colors in this way they will appear to be at the same level of saturation, something that simply adding or subtracting numbers will not achieve.
Be aware that since values are clamped at [0, 255], if you keep shifting colors, then feeding them back into this process, you can destroy information about the proportion of red, green and blue in the source color. For this reason, keep the original color saved and try to use that as your input each time.
Since your question asked specifically about gradients though, this is how you would go between two color values:
// Suppose you have a container which is X pixels high and you want to insert a 1-pixel tall
// element at each pixel, going vertically
var min = Math.min;
var max = Math.max;
var round = Math.round;
function get_color_for_height(startColor, endColor, height, row) {
var scale = row/height;
var r = startColor[red] + scale*(endColor[red] - startColor[red]);
var b = startColor[blue] + scale*(endColor[blue] - startColor[blue]);
var g = startColor[green] + scale*(endColor[green] - startColor[green]);
return {
r: round(min(255, max(0, r))),
g: round(min(255, max(0, g))),
b: round(min(255, max(0, b)))
}
}
// some psuedo-code using an imaginary framework
for(var h = 0; h < height; h++) {
var div = new Element('div');
div.height = 1;
div.backgroundColor = get_color_for_height(start, end, height, h);
container.insert('top', div);
}