Skip to content

Instantly share code, notes, and snippets.

@ZucchiniZe
Last active April 29, 2017 09:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ZucchiniZe/1612e05ab743a67eae1a629d673c034c to your computer and use it in GitHub Desktop.
Save ZucchiniZe/1612e05ab743a67eae1a629d673c034c to your computer and use it in GitHub Desktop.
a rainbow thing. takes an old color an increments it up in a rainbow step
interface Color {
r: number
g: number
b: number
}
function hexToColor(hex: string): Color {
let color: Color = {} as any
color.r = parseInt(hex.slice(0, 2), 16)
color.g = parseInt(hex.slice(2, 4), 16)
color.b = parseInt(hex.slice(4, 6), 16)
return color
}
function colorToHex({r, g, b}: Color): string {
// some bitshifty magic found on stack overflow
// ref: http://stackoverflow.com/a/5624139/3453207
return ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)
}
function incrementColor(oldColor: string, skip: number = 12): string {
let color: Color = hexToColor(oldColor)
// check if b is at the end to reset everything
if ((color.b + skip) > 255) {
return colorToHex({r:0,g:0,b:0})
}
// if color is less than 255 and not greater than 255, increment up by `skip`
if (color.r <= 255 && !((color.r + skip) > 255)) {
color.r += skip
} else if (color.g <= 255 && !((color.g + skip) > 255)) {
color.g += skip
} else if (color.b <= 255 && !((color.b + skip) > 255)) {
color.b += skip
}
return colorToHex(color)
}
let color: string = '000000'
document.body.style.backgroundColor = '#' + color
setInterval(() => {
color = incrementColor(color)
document.body.style.backgroundColor = '#' + color
}, 300)
// let iterations: number = 124
// for (var index = 0; index < iterations; index++) {
// color = incrementColor(color)
// console.log(index, color)
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment