Last active
February 11, 2024 22:25
-
-
Save gpiffault/e7ddc4a1eae1eb92dc52 to your computer and use it in GitHub Desktop.
Multi-stop color gradient (AMD module)
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
// Color interpolation | |
// Usage: | |
// var myGradient = Gradient([ | |
// [50, "#9999ff"], | |
// [100, "#99ff99"], | |
// [150, "#ff9999"] | |
// ]); | |
// myGradient(75); // returns "#99cccc" | |
define([], function () { | |
function Piecewise(xs, ys) { | |
return function(x) { | |
//out of bounds | |
if (x <= xs[0]) return ys[0]; | |
if (x >= xs[xs.length - 1]) return ys[xs.length - 1]; | |
//bisect | |
var lo = 0, hi = xs.length - 1; | |
while (hi - lo > 1) { | |
var mid = (lo + hi) >> 1; | |
if (x < xs[mid]) hi = mid; | |
else lo = mid; | |
} | |
//project | |
return ys[lo] + (ys[hi] - ys[lo]) / (xs[hi] - xs[lo]) * (x - xs[lo]); | |
}; | |
} | |
function formatHexPart(number) { | |
var result = Math.round(number).toString(16); | |
while (result.length < 2) result = "0" + result; | |
return result.substr(0, 2); | |
} | |
function Gradient(stops) { | |
var xs = []; | |
var ys_r = []; | |
var ys_g = []; | |
var ys_b = []; | |
stops.forEach(function (stop) { | |
xs.push(stop[0]); | |
ys_r.push(parseInt(stop[1].substr(1, 2), 16)); | |
ys_g.push(parseInt(stop[1].substr(3, 2), 16)); | |
ys_b.push(parseInt(stop[1].substr(5, 2), 16)); | |
}); | |
pw_r = Piecewise(xs, ys_r); | |
pw_g = Piecewise(xs, ys_g); | |
pw_b = Piecewise(xs, ys_b); | |
return function (x) { | |
return "#" + formatHexPart(pw_r(x)) + | |
formatHexPart(pw_g(x)) + | |
formatHexPart(pw_b(x)); | |
}; | |
} | |
return Gradient; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment