Skip to content

Instantly share code, notes, and snippets.

@jabney
Created May 6, 2017 15:42
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 jabney/86ab61dbb8eebc23421af3e1ee2893e6 to your computer and use it in GitHub Desktop.
Save jabney/86ab61dbb8eebc23421af3e1ee2893e6 to your computer and use it in GitHub Desktop.
keyframeInterplation function using binary search
function keyframeInterpolate(keyframes, time, timing, lib) {
const first = 0
const last = keyframes.length - 1
// Clamp time to [0, 1]
time = Math.max(Math.min(time, 1), 0)
if (!Array.isArray(keyframes) || !keyframes.length) {
return lib.zero()
}
if (keyframes.length === 1) {
return keyframes[first].value
}
if (time < keyframes[first].stop) {
return keyframes[first].value
}
if (time > keyframes[last].stop) {
return keyframes[last].value
}
const pairs = []
keyframes.reduce((a, b) => {
pairs.push([a, b])
return b
})
const pair = search.binary(pairs, time, pair => {
const [a, b] = pair
if (time < a.stop) { return -1 }
else if (time > b.stop) { return 1 }
return 0
})
if (pair != null) {
const [a, b] = pair
const t_segment = (time - a.stop) / (b.stop - a.stop)
const interpolate = timingToInterpFn(timing, lib)
return interpolate(a.value, b.value, t_segment)
}
return lib.zero()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment