Created
March 5, 2019 22:20
-
-
Save PEZ/2f5d4c39323e1612425ea3b1ea852425 to your computer and use it in GitHub Desktop.
Adaption of tween function to use requestAnimationFrame
This file contains hidden or 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
| (ns tween | |
| "Simple tweening of values inside a map atom.") | |
| (defn easeOutQuad | |
| [elapsed-t duration] | |
| (let [dt (/ elapsed-t duration)] | |
| (* dt (- 2 dt)))) | |
| (defn easeLinear | |
| [elapsed-t duration] | |
| (let [dt (/ elapsed-t duration)] | |
| dt)) | |
| #?(:cljs | |
| (defn tween-to! [state easing key new-value duration] | |
| (let [anim-key (keyword (str (name key) "-anim")) | |
| initial-value (key @state)] | |
| (letfn [(tick [_] | |
| (let [a-map (anim-key @state) | |
| t (- (.now js/Date) (::t0 a-map))] | |
| (if (< t duration) | |
| (let [progress (easing t duration) | |
| new-val (+ (::initial-value a-map) | |
| (* progress (::delta a-map)))] | |
| (swap! state assoc key new-val | |
| ::ticker (js/requestAnimationFrame tick))) | |
| (do | |
| (js/cancelAnimationFrame (::ticker a-map)) | |
| (swap! state dissoc anim-key) | |
| (swap! state assoc key new-value)))))] | |
| (swap! state assoc anim-key | |
| {::t0 (.now js/Date.) | |
| ::ticker (js/requestAnimationFrame tick) | |
| ::delta (- new-value initial-value) | |
| ::initial-value initial-value})))) | |
| :clj | |
| (defn tween-to! [state easing key new-value duration] | |
| (swap! state assoc key new-value))) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment