Lighten hex code in javascript
algorithm, hex, javascript
Solution
An easy way to lighten up a color is linear interpolation with white. In the same way, a color can be darkened by interpolating with black.
Here's a function that takes a color string and changes the brightness indicated by `light`:
function hex2(c) {
c = Math.round(c);
if (c < 0) c = 0;
if (c > 255) c = 255;
var s = c.toString(16);
if (s.length < 2) s = "0" + s;
return s;
}
function color(r, g, b) {
return "#" + hex2(r) + hex2(g) + hex2(b);
}
function shade(col, light) {
// TODO: Assert that col is good and that -1 < light < 1
var r = parseInt(col.substr(1, 2), 16);
var g = parseInt(col.substr(3, 2), 16);
var b = parseInt(col.substr(5, 2), 16);
if (light < 0) {
r = (1 + light) * r;
g = (1 + light) * g;
b = (1 + light) * b;
} else {
r = (1 - light) * r + light * 255;
g = (1 - light) * g + light * 255;
b = (1 - light) * b + light * 255;
}
return color(r, g, b);
}
When `light` is negative, the color is darkened; -1 always yields black. When `light` is positive, the color is lightened, 1always yields white. Finally, 0 always yields the original color:
alert(shade("#2ac0a3", 0.731));
Problem
I want to have the user be able to enter a random hex color and my javascript code would print out a lighter version of that color (some sort of algorithm so to speak) A quick example of how I want the colors to change. What the user inputs: #2AC0A3 What it spits out: #C6EEE6 Thanks so much to anyone who can help!