Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Calculate brighter colour

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 
like image 590
Ozzy Avatar asked Jun 22 '11 17:06

Ozzy


People also ask

How do you calculate dark colors?

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.

How do you lighten a darken or hex color?

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 ).

How do you saturate RGB values?

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.


1 Answers

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  **/ 
like image 154
Nobody Avatar answered Sep 22 '22 21:09

Nobody