Javascript Calculate darker colour

calculator, colors, javascript, jquery

Solution

You can change

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

to

return '#' +
   ((0|(1<<8) + r * (1 - percent / 100)).toString(16)).substr(1) +
   ((0|(1<<8) + g * (1 - percent / 100)).toString(16)).substr(1) +
   ((0|(1<<8) + b * (1 - percent / 100).toString(16)).substr(1);

will fix your problem. demo.

But darker color is not a good definition. Darker can be interpreted as less brightness or less saturation. So the better approach is to convert the RGB color space to HSB color space, and tweak the S/B channels, then convert them back.

A little explanation on why negative value to original code is not OK.

Give -100 as percent, and some channel, say r, less than 128. Then

r + (256 - r) * percent / 100

is less than 0, after plus `1 << 8` = 256

((0|(1<<8) + r + (256 - r) * percent / 100)

is less than 256.

Take a number less than 256 will generate at most two hex digits by calling `toString(16)`, so `.substr(1)` will contain 0 or 1 digit only. By combining all these wrong digits together will not generate a proper color in hex representation.

Problem

how can i change this calculation to a darker and not brighter color? ``` 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); } ``` src = JavaScript Calculate brighter colour demo http://jsbin.com/utavax/3/edit

Original source

Related problems