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.

Owner

mlocati commented Jun 16, 2016

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

output

@Majo1996

This comment has been minimized.

Majo1996 commented Jun 1, 2017

Nice, thank you!

@kishore-indraganti

This comment has been minimized.

kishore-indraganti commented Aug 8, 2017

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

@anandbaskaran

This comment has been minimized.

anandbaskaran commented Nov 9, 2017

Thanks!

@ruaanvds

This comment has been minimized.

ruaanvds commented Feb 15, 2018

@mlocati, thanks for a succinct, clean solution!

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