Created
March 30, 2012 08:24
-
-
Save sanand0/2249568 to your computer and use it in GitHub Desktop.
Color manipulation library
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
// Internal color conversion | |
// Converts `#ffffff` to `(255, 255, 255)` | |
function _colornum(color) { | |
var l = color.length; | |
return [ | |
parseInt(color.slice(l-6,l-4), 16), | |
parseInt(color.slice(l-4,l-2), 16), | |
parseInt(color.slice(l-2,l-0), 16) | |
]; | |
} | |
// Sample usage: | |
// | |
// gradient(0.4, ((-1, '#ff0000'), (0, '#ffffff'), (1, '#00ff00'))) | |
// | |
// interpolates 0.4 between -1 - 0 - +1 and returns an in-between color | |
// as #RRGGBB | |
function gradient(x, ranges) { | |
if (x <= ranges[0][0]) { return ranges[0][1]; } | |
if (x >= ranges[ranges.length-1][0]) { return ranges[ranges.length-1][1]; } | |
for (var i=0, range; range = ranges[i]; i++) { | |
var start = range[0], color = range[1]; | |
if (x < start) { break; } | |
} | |
var p = (x - ranges[i-1][0]) / (ranges[i][0] - ranges[i-1][0]); | |
var a = _colornum(ranges[i-1][1]); | |
var b = _colornum(ranges[i][1]); | |
return 'rgb(' + | |
Math.round((a[0]*(1.0-p) + b[0]*p)) + ',' + | |
Math.round((a[1]*(1.0-p) + b[1]*p)) + ',' + | |
Math.round((a[2]*(1.0-p) + b[2]*p)) + ')'; | |
} | |
// Some standard gradients | |
// -------------------------------------------------------------------------- | |
RYG = [[ 0.0, '#ff0000'], [0.5, '#ffff00'], [1.0, '#00ff00']] | |
RYG_1 = [[-1.0, '#ff0000'], [0.0, '#ffff00'], [1.0, '#00ff00']] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For good palettes, visit http://colorbrewer2.org/