Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Javascript color scale from 0% to 100%, rendering it from red to yellow to green
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);
}
@mlocati

This comment has been minimized.

Copy link
Owner Author

commented Jun 16, 2016

Here's the color scale (from 0 to 100):

output

@Majo1996

This comment has been minimized.

Copy link

commented Jun 1, 2017

Nice, thank you!

@kishore-indraganti

This comment has been minimized.

Copy link

commented Aug 8, 2017

What if i want to use red to green to blue ?

@anandbaskaran

This comment has been minimized.

Copy link

commented Nov 9, 2017

Thanks!

@ruaanvds

This comment has been minimized.

Copy link

commented Feb 15, 2018

@mlocati, thanks for a succinct, clean solution!

@roboriaan

This comment has been minimized.

Copy link

commented Feb 14, 2019

A slight modification to pass in a min and max.
It should calculate the same as excel does with it's color scales :

function perc2color(perc,min,max) {
            var base = (max - min);

            if (base == 0) { perc = 100; }
            else {
                perc = (perc - min) / base * 100; 
            }
            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);
        }
@dozzes

This comment has been minimized.

Copy link

commented May 22, 2019

How to draw a rectangle with this gradient color filling in HTML?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.