Last active
January 15, 2025 16:07
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// License: MIT - https://opensource.org/licenses/MIT | |
// Author: Michele Locati <[email protected]> | |
// 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); | |
} |
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);
}
cool thanks
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
How did I not think of that? Thank you very much. =)