Skip to content

Instantly share code, notes, and snippets.

@Suppenhuhn79
Created July 6, 2021 13:09
Show Gist options
  • Save Suppenhuhn79/c69a798b7ef0d94fb90c56d8d2901489 to your computer and use it in GitHub Desktop.
Save Suppenhuhn79/c69a798b7ef0d94fb90c56d8d2901489 to your computer and use it in GitHub Desktop.
JavaScript Gradient Color Calculation

JavaScript Gradient Color Calculation

This is a small function to calculate a color (RGB) at a specific gradient location.

function gradientColor(percentage, stops)
  • percentage is the desired position. It is a number between (including) 0 and 1. Values less then 0 will be set to 0, values greater than 1 will be set to 1.
  • stops is an array of the gradient stops (see example).
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
</head>
<body>
<script src="gradientColor.js"></script>
<script>
const stops = [
{
position: 0,
rgb: [0, 255, 0]
},
{
position: 0.5,
rgb: [255, 255, 0]
},
{
position: 1,
rgb: [255, 0, 0]
}
];
for (let v = -0.1; v <= 1.1; v += 0.1)
{
let cMix = gradientColor(v, stops)
/* dim */
const dim = 0.6;
let cDim = [];
for (let c of cMix)
{
cDim.push(c * dim);
};
let e = document.createElement("div");
e.innerText = Math.round(v * 10) / 10;
e.style.backgroundColor = "rgb(" + cMix.join(",") + ")";
e.style.border = "2px solid rgb(" + cDim.join(",") + ")";
e.style.borderRadius = "0.3em";
e.style.padding = "0.3rem";
e.style.marginBottom = "0.5rem";
document.body.appendChild(e);
};
</script>
</body>
</html>
function gradientColor(percentage, stops)
{
percentage = Math.max(Math.min(1, percentage), 0);
for (let i = 0, j = stops.length - 1; i < j; i += 1)
{
let floor = stops[i].position;
let ceil = stops[i + 1].position;
if ((percentage >= floor) && (percentage <= ceil))
{
let sizeCeil = (percentage - floor) / (ceil - floor);
let sizeFloor = 1 - sizeCeil;
let cMix = [];
for (let c = 0, cc = stops[i].rgb.length; c < cc; c += 1)
{
cMix.push(stops[i].rgb[c] * sizeFloor + stops[i + 1].rgb[c] * sizeCeil);
};
return cMix;
};
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment