How to Lighten or Darken HEX or RGB color in PHP and JavaScript

Hi Guys,

Just a thought and following up on my previous post is a function that you can use in your PHP code to brighten or darken a HEX or a RGB color, For color manipulation in JavaScript you can look at this cool library https://github.com/jfsiii/chromath

PHP Function

Below is the function you can use to make on the fly adjustment to colors

For sure above function can have less lines but for simplicity and readability I think putting it as above makes sense.

Usage – Lightning Colors

Usage – Darkening Colors

 

Now lets check the JavaScript implementation of this function.

JavaScript Equivalent Function For Lightening and Darkening HEX or RGB Colors

You can definitely do better job with shift operators but I always think of readability of code first. The code below can be shrunk but at least you get the Idea what’s happening in a typical way

Usage 1 – Lighten

Now lets check how we can use the same function to Darken our Hex or RBG colors

Usage 2 – Darken

I hope this helps.

Got a better implementation of these function. I would love to know and this will help my readers too. Share it, leave your comments

Cheers

 

VN:F [1.9.22_1171]
Rating: 5.0/5 (2 votes cast)
VN:F [1.9.22_1171]
Rating: +2 (from 2 votes)
How to Lighten or Darken HEX or RGB color in PHP and JavaScript, 5.0 out of 5 based on 2 ratings

Comments

  1. Actually I suggest changing this part for the PHP implementantion:

    $r = round($r – ($r*$percentage_adjuster));
    to
    $r = round($r – (255*$percentage_adjuster));

    For the three colors. On your current implementation you’re chaning the color based on a parcentage of itself, and not on a max scale percentage. So, darkening a color in 10% should reduce the color ($r) by 25,5 points (10% of 255) and not by 10% of it’s current value.

  2. It does not works for me with black color #000000, color stills every time #000000

Leave a Reply