Skip to content

Instantly share code, notes, and snippets.

@rhwlo
Created March 23, 2016 19:24
Show Gist options
  • Save rhwlo/cd1b00763af2a415323d to your computer and use it in GitHub Desktop.
Save rhwlo/cd1b00763af2a415323d to your computer and use it in GitHub Desktop.
JS to create a sine-rainbow
// Translated from code from Sam Kimbrel and Charlie Loyd
// via http://basecase.org/env/on-rainbows
const PHI = (1 + Math.pow(5, 0.5)) / 2;
function sinebow(hue) {
// Choose a color from a sin^2-softened rainbow.
var red = Math.pow(Math.cos(Math.PI * hue), 2) * 255;
var green = Math.pow(Math.cos(Math.PI * (hue + 1/3)), 2) * 255;
var blue = Math.pow(Math.cos(Math.PI * (hue + 2/3)), 2) * 255;
return [Math.floor(red), Math.floor(green), Math.floor(blue)];
}
function choose_hex_color(n) {
// Choose color number `n` from the sinebow using the angle of phi to reduce
// collision possibilities, and returning it as a hex-formatted color.
var color = sinebow(n * PHI);
return "#" + color.map(function (channel) {
var hex = channel.toString(16);
if (channel < 16) {
hex = '0' + hex;
}
return hex;
}).join('');
}
module.exports = {'sinebow': sinebow, 'choose_hex_color': choose_hex_color };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment