I have a colour value in JS as a string
#ff0000
How would I go about programatically calculating a brighter/lighter version of this colour, for example #ff4848
, and be able to calculate the brightness via a percentage, e.g.
increase_brightness('#ff0000', 50); // would make it 50% brighter
For shades, multiply each component by 1/4, 1/2, 3/4, etc., of its previous value. The smaller the factor, the darker the shade. For tints, calculate (255 - previous value), multiply that by 1/4, 1/2, 3/4, etc. (the greater the factor, the lighter the tint), and add that to the previous value (assuming each.
Just pass in a string like "3F6D2A" for the color ( col ) and a base10 integer ( amt ) for the amount to lighten or darken. To darken, pass in a negative number (i.e. -20 ).
To saturate a color we need to increase the difference between the lowest and highest RGB value. This will move it toward a pure hue. If we want to keep the lightness the same, we're going to need to increase the highest value and decrease the lowest value by an equal amount.
function increase_brightness(hex, percent){ // strip the leading # if it's there hex = hex.replace(/^\s*#|\s*$/g, ''); // convert 3 char codes --> 6, e.g. `E0F` --> `EE00FF` if(hex.length == 3){ hex = hex.replace(/(.)/g, '$1$1'); } var r = parseInt(hex.substr(0, 2), 16), g = parseInt(hex.substr(2, 2), 16), b = parseInt(hex.substr(4, 2), 16); return '#' + ((0|(1<<8) + r + (256 - r) * percent / 100).toString(16)).substr(1) + ((0|(1<<8) + g + (256 - g) * percent / 100).toString(16)).substr(1) + ((0|(1<<8) + b + (256 - b) * percent / 100).toString(16)).substr(1); } /** * ('#000000', 50) --> #808080 * ('#EEEEEE', 25) --> #F2F2F2 * ('EEE , 25) --> #F2F2F2 **/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With