Skip to content

Instantly share code, notes, and snippets.

@estrattonbailey
Last active January 18, 2019 15:37
Show Gist options
  • Save estrattonbailey/1e73c6219aed00e049fdb17d1afe6bcd to your computer and use it in GitHub Desktop.
Save estrattonbailey/1e73c6219aed00e049fdb17d1afe6bcd to your computer and use it in GitHub Desktop.
Color Tweening
function hexToRGB (c) {
const a = []
const steps = [0, 2, 4]
for (let i = 0; i < 3; i++) {
a[i] = c.slice(steps[i], steps[i] + 2)
}
return {
r: parseInt(a[0], 16),
g: parseInt(a[1], 16),
b: parseInt(a[2], 16)
}
}
function pad (c) {
return c.length === 1 ? '0' + c : '' + c
}
function hex (v) {
return pad(Math.ceil(v).toString(16))
}
function grade (c1, c2, d, callback) {
let i = 0
const frames = d / 60
const _c1 = hexToRGB(c1)
const _c2 = hexToRGB(c2)
const dr = _c2.r - _c1.r > 0 ? 1 : -1
const dg = _c2.r - _c1.g > 0 ? 1 : -1
const db = _c2.b - _c1.b > 0 ? 1 : -1
const cr = (Math.abs(_c1.r - _c2.r) * dr) / frames
const cg = (Math.abs(_c1.g - _c2.g) * dg) / frames
const cb = (Math.abs(_c1.b - _c2.b) * db) / frames
let { r, g, b } = Object.assign({}, _c1)
callback(c1)
const interval = node.setInterval(() => {
i++
if (i >= frames) {
node.clearInterval(interval)
callback(c2)
return
}
r += cr
g += cg
b += cb
callback(
hex(r) + hex(g) + hex(b)
)
}, 1000 / 60)
}
grade('000000', 'abcdef', 1000, hex => {
console.log(hex)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment