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

 

Comments

  1. You used -5 for both lighten and darken at the bottom here. Check out https://github.com/Qix-/color and https://bgrins.github.io/TinyColor/

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

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

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.