Created
May 6, 2017 15:42
-
-
Save jabney/86ab61dbb8eebc23421af3e1ee2893e6 to your computer and use it in GitHub Desktop.
keyframeInterplation function using binary search
This file contains 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 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