Skip to content

Instantly share code, notes, and snippets.

@davebarnwell
Last active December 15, 2022 09:30
Show Gist options
  • Save davebarnwell/bd8483f5562aa46812b90433e5bbd6a3 to your computer and use it in GitHub Desktop.
Save davebarnwell/bd8483f5562aa46812b90433e5bbd6a3 to your computer and use it in GitHub Desktop.
Algorithm to create heatmap colors
<?php
class Colour
{
/**
* Maps a float value to a CSS HSL color
*
* 0 : blue
* 0.25 : cyan
* 0.5 : green
* 0.75 : yellow
* 1 : red
*
* @param float $value a value between 0 and 1 inclusive
* @param int $max_hue_angle default 240, for blue > cyan > green > yellow > red gradients
*
* @return string a CSS HSL() color definition string
*/
public static function valueToHSLColour(float $value, int $max_hue_angle = 240): string
{
if ($max_hue_angle < 0 || $max_hue_angle > 360) {
throw new \InvalidArgumentException('max_hue_angle must be between 0 and 360 inclusive');
}
if ($value < 0 || $value > 1) {
throw new \InvalidArgumentException('value must be between 0 and 1 inclusive');
}
$hue = (1.0 - $value) * $max_hue_angle;
return sprintf("hsl(%d, 100%%, 50%%)", $hue);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment