Last active
September 8, 2016 16:57
-
-
Save ycmjason/1776ffb39a04c1be9dfacb7b18071500 to your computer and use it in GitHub Desktop.
Return a list of colors([r, g, b]) that transit from/to all colors(hex) in the list.
This file contains hidden or 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
spectrum = getSpectrum(20, ['#2E7D32', '#ffee58', '#B71C1C']); | |
console.log(spectrum); | |
// [[46,125,50],[67,136,54],[88,148,58],[109,159,61],[130,170,65],[151,182,69],[171,193,73],[192,204,77],[213,215,80],[234,227,84],[255,238,88],[248,217,82],[241,196,76],[233,175,70],[226,154,64],[219,133,58],[212,112,52],[205,91,46],[197,70,40],[190,49,34]] | |
/* we can apply the color to css */ | |
$('div').css('background-color', 'rgb(' + spectrum[3] + ')'); |
This file contains hidden or 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
function getSpectrum(n, colors){ | |
function hexToRGB(h){ | |
var hexToDec = function(h){ | |
return parseInt(h, 16); | |
}; | |
h = (h.charAt(0) == "#") ? h.substring(1, 7): h; | |
rgbHex = [h.substring(0, 2), h.substring(2, 4), h.substring(4, 6)]; | |
return rgbHex.map(hexToDec); | |
} | |
function _getSpectrum(n, from, to){ | |
// calculate the step for r/g/b. | |
var step = []; | |
var step_acc = []; | |
for(var i = 0; i <= 2; i++){ | |
step[i] = (to[i]-from[i])/n; | |
} | |
// generate n colors, i.e. a spectrum | |
var spectrum = []; | |
for(var i = 0; i < n; i++){ | |
var color = []; | |
for(var j = 0; j <= 2; j++){ | |
color[j] = Math.round(from[j] + step[j] * i); | |
} | |
spectrum.push(color); | |
} | |
return spectrum; | |
} | |
colors = colors.map(hexToRGB); | |
var spectrum = []; | |
var m = Math.floor(n / (colors.length - 1)); | |
var acc = n; | |
for(var i = 0; i < colors.length - 1; i++){ | |
acc -= m; | |
if(acc > 0 && acc < m){ m += acc; } | |
spectrum = spectrum.concat(_getSpectrum(m, colors[i], colors[i+1])); | |
} | |
return spectrum; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can see the live example at here.