Skip to content

Instantly share code, notes, and snippets.

@mlocati
Last active May 1, 2024 10:55
Show Gist options
  • Save mlocati/7210513 to your computer and use it in GitHub Desktop.
Save mlocati/7210513 to your computer and use it in GitHub Desktop.
Javascript color scale from 0% to 100%, rendering it from red to yellow to green
// License: MIT - https://opensource.org/licenses/MIT
// Author: Michele Locati <michele@locati.it>
// Source: https://gist.github.com/mlocati/7210513
function perc2color(perc) {
var r, g, b = 0;
if(perc < 50) {
r = 255;
g = Math.round(5.1 * perc);
}
else {
g = 255;
r = Math.round(510 - 5.10 * perc);
}
var h = r * 0x10000 + g * 0x100 + b * 0x1;
return '#' + ('000000' + h.toString(16)).slice(-6);
}
@andyg2
Copy link

andyg2 commented Jun 21, 2020

Sorry, but how to print it on HTML, anyone please show me a way.

var color = perc2color(40);
document.body.style.backgroundColor = color;

@crepehat
Copy link

crepehat commented Jul 3, 2020

You've made my day. Thankyou.

@afarbman
Copy link

Thank you very much! awesome gist

@EsraaQandel
Copy link

wanna use a different gradient? more flexibility with colors?
Check this example out
http://jsfiddle.net/dj0xmazk/13/

@aymyo
Copy link

aymyo commented Jan 13, 2021

Exactly what I needed, thank you!

@octameter
Copy link

Nice!

@aderbas
Copy link

aderbas commented Jan 31, 2022

Can anyone help with the reverse? From green to red (0 - green .... 100 - red)

@mlocati
Copy link
Author

mlocati commented Jan 31, 2022

@aderbas simply call perc2color(100 - yourPercentage)

@aderbas
Copy link

aderbas commented Feb 1, 2022

How did I not think of that? Thank you very much. =)

@sambenne
Copy link

A PHP version

function percentageToColour($percentage): string
{
    $r = $g = $b = 0;
    if ($percentage < 50) {
        $r = 255;
        $g = round(5.1 * $percentage);
    } else {
        $g = 255;
        $r = round(510 - 5.10 * $percentage);
    }
    $h = $r * 0x10000 + $g * 0x100 + $b * 0x1;
    return '#'.substr(('000000'.dechex($h)), -6);
}

@aktentasche
Copy link

cool thanks

@jbundziow
Copy link

Great! It works well in my project. Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment